Reputation: 3929
Hi i have an xml in the following format generated from a web service.
<root>
<item>
<name>test</name>
<description>test description</description>
<link>http://xxx</link>
</item>
</root>
I read the file
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
now that I have doc, how would i get the and for each
and put it into a object call Item
public class Item {
private final String name;
private final String desc;
private final String link;
public Item(final String name, final String desc, final String link) {
super();
this.name = name;
this.desc = desc;
this.link = link;
}
// ... getters for name and desc
}
I look at examples of dom element but they seem confusing. Whats the most easiest/efficent way to parse XML into java object. Can i get an example?
Using xstream works.
I did
final XStream xstream = new XStream(new DomDriver());
xstream.alias("root", LineItem.class);
xstream.aliasField("name", Item.class, "name");
xstream.aliasField("description", Item.class, "desc");
xstream.aliasField("link", Item.class, "link");
xstream.fromXml(xml);
Upvotes: 1
Views: 3524