您好我有一个从Web服务生成的以下格式的xml。
<root>
<item>
<name>test</name>
<description>test description</description>
<link>http://xxx</link>
</item>
</root>
我读了文件
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
既然我有文档,我将如何获得每个
并将其放入对象调用项
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
}
我看一下dom元素的例子,但它们似乎令人困惑。什么是将XML解析为java对象的最简单/最有效的方法。我可以举个例子吗?
使用xstream工作。
我做了
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);