如何使用rometools正确解析RSS XML?

时间:2017-03-23 11:06:30

标签: java xml rss

我正在尝试用rometools解析RSS XML文件,但我无法让它工作。下面的Product类具有以下RSS XML文件中的所有元素。但我似乎无法正确地将文件映射到实体。

RSS XML文件:

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>Test Store</title>
<link>http://www.example.com</link>
<description>An example item from the feed</description>
<item>
<g:id>DB_1</g:id>
<g:title>Dog Bowl In Blue</g:title>
<g:description>Solid plastic Dog Bowl in marine blue color</g:description>
<g:link>http://www.example.com/bowls/db-1.html</g:link>
<g:image_link>http://images.example.com/DB_1.png</g:image_link>
<g:brand>Example</g:brand>
<g:condition>new</g:condition>
<g:availability>in stock</g:availability>
<g:price>9.99 GBP</g:price>
<g:shipping>
<g:country>UK</g:country>
<g:service>Standard</g:service>
<g:price>4.95 GBP</g:price>
</g:shipping>
<g:google_product_category>Animals &gt; Pet Supplies</g:google_product_category>
<g:custom_label_0>Made in Waterford, IE</g:custom_label_0>
</item>
</channel>
</rss>

解析方法是:

Product product = new Product();

try {
    SyndFeedInput input = new SyndFeedInput();

    SyndFeed feed = input.build(new XmlReader(file));


    Namespace ns = Namespace.getNamespace("g", "http://base.google.com/ns/1.0");

    for (SyndEntry entry : feed.getEntries()) {
        for (Element element : entry.getForeignMarkup()) {
            product.setId(element.getAttribute("id", ns).getValue()); // **id
        }
    }

    System.out.println(product.getId());
} catch (Exception e) {
    ex.printStackTrace();
}

带有// **id注释的部分返回NullPointerException。

这里有什么问题?如何使这个工作?

1 个答案:

答案 0 :(得分:0)

搞定了!不需要Namespace部分,for就像这样:

for (SyndEntry entry : feed.getEntries()) {
    for (Element element : entry.getForeignMarkup()) {
        if (element.getQualifiedName().equalsIgnoreCase("g:id")) {
                product.setId(element.getValue());
        }
    }
}