我想使用jackson rapid xml的XMLMapper解析一个XML文件并转换为pojo类。我完成了这项工作,但最后我遇到了问题。
Xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
<title>1st Title</title>
<link>http://www.eample.com</link>
<language>en-US</language>
<pubDate>Thu, 16 Jun 2016 04:37:53 +0000</pubDate>
<item>
<title>The DI Wire’s QA With CNL CEO Tom Sittema</title>
<link>http://www.eample.com</link>
<description>5 lines description</description>
<pubDate>Wed, 15 Jun 2016 16:30:07 +0000</pubDate>
</item>
<item>
<title>2nd title</title>
<link>http://www.globest.com/sites/paulbubny/2016/06</link>
<description>5 lines description</description>
<pubDate>Wed, 15 Jun 2016 16:28:40 +0000</pubDate>
</item>
</channel>
</rss>
我只想要Item标签包含。但问题是我只得到第二个项目标签包含。
Rss.java :
@JacksonXmlRootElement(localName = "rss")
public class Rss {
private String version;
private Channel channel;
//setters & getters
}
Channel.java :
public class Channel {
private String title;
private String link;
private String description;
private String language;
private String lastBuildDate;
private String pubDate;
private String atom;
private String generator;
private String href;
private String rel;
private String type;
@XmlElement(name = "item")
@XmlElementWrapper(name = "wrapitem")
private List<Item> item;
//Setters & getters
}
Item.java :
public class Item {
private String title;
private URL link;
private String description;
private String pubDate;
private String category;
private String source;
private String guid;
private String isPermaLink;
private String url;
//setter & getters
}
Main.java :
public class MainClass {
public static void main(String[] args) {
try {
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new xmlMapper(module); Rss rss = xmlMapper.readValue(new File("/home/Address.xml"), Rss.class);
Channel channel = rss.getChannel();
System.out.println(channel);
List<Item> item = channel.getItem();
System.out.println(item);
if (item != null) {
for (Item a : item) {
System.out.println(a.getTitle());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
2nd Title
null
请帮助我确定为什么它会输出这样的输出,首先必须打印第一个标题然后打印第二个标题,而不是为什么这个代码会给出这样的输出。
先谢谢。