그냥 대충 참고만 했음
# 응답XML
<items>
<item>
<id>1</id>
<name>사과</name>
<price>1000</price>
</item>
<item>
<id>2</id>
<name>배</name>
<price>2000</price>
</item>
</items>
<JAXB>
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
public class XmlToDtoParser {
public static void main(String[] args) {
String xmlResponse = "<items>" +
"<item><id>1</id><name>사과</name><price>1000</price></item>" +
"<item><id>2</id><name>배</name><price>2000</price></item>" +
"</items>";
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Items.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xmlResponse);
Items items = (Items) unmarshaller.unmarshal(reader);
for (Item item : items.getItems()) {
System.out.println("ID: " + item.getId());
System.out.println("Name: " + item.getName());
System.out.println("Price: " + item.getPrice());
System.out.println();
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
-----
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "items")
public class Items {
private List<Item> items;
public List<Item> getItems() {
return items;
}
@XmlElement(name = "item")
public void setItems(List<Item> items) {
this.items = items;
}
}
----
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "item")
public class Item {
private int id;
private String name;
private int price;
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
@XmlElement
public void setPrice(int price) {
this.price = price;
}
}
JAVA XML 파싱방법 Apache digester 이용 (0) | 2023.04.09 |
---|---|
log4jdbc 이클립스 콘솔 SQL 포멧팅 되도록 찍기 (0) | 2017.08.09 |
오라클 전화번호 쪼개기 (0) | 2017.07.11 |