如何将xml解析为java对象?
您好,我有一个从 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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XStream 可以将xml解析为java对象。 XML 不需要由 XStream 创建。
示例代码在这里
希望这会对您有所帮助。
XStream can parse xml to java objects. XML need not to be created by XStream.
Example Code is here
Hope this would help you.