简体   繁体   English

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

[英]how to correctly parse RSS XML with rometools?

I'm trying to parse a RSS XML file with rometools , but I haven't been able to get it working. 我正在尝试使用rometools解析RSS XML文件,但无法使其正常工作。 The Product class bellow, has all the elements from the following RSS XML file. 下面的Product类具有来自以下RSS XML文件的所有元素。 But I can't seem to be able to corretly map the file to the entity. 但是我似乎无法正确地将文件映射到实体。

RSS XML file: 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>

The parsing method is: 解析方法为:

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();
}

The part with the // **id comment returns a NullPointerException. 带有// **id注释的部分返回NullPointerException。

What's wrong here? 怎么了 How to get this working? 如何使它工作?

Got it working! 得到它的工作! The Namespace part is not needed and the for is like this: 不需要Namespace部分,for如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM