使用JDOM进行XML解析失败

时间:2012-05-05 13:34:17

标签: xml parsing xml-parsing jdom

我正在使用JDOM解析器来解析使用feedrinse创建的XML。

XML位于:http://www.feedrinse.com/services/rinse/?rinsedurl=396ac3b0142bb6360003c8dbac4f8d47

我的代码是解析每个title,link,pubDate元素并将它们存储在我发送到前端的新XML中。这是我的代码:

String temp = "http://www.feedrinse.com/services/rinse/?rinsedurl=396ac3b0142bb6360003c8dbac4f8d47";
String XMLstr="<FEED>";

SAXBuilder builder = new SAXBuilder();
URL url= new URL(temp);
Document doc = null;                
 try{
    doc=builder.build(url);             
    Element root = doc.getRootElement();
    //List children = root.getChildren();
    List list = root.getChildren("item");
    XMLstr+="<children>"+list.size()+"</children>";
    for (int i = 0; i < list.size(); i++) {
           Element node = (Element) list.get(i);
           String title=node.getChildText("title").toString();
           XMLstr+="<title>"+title+"</title>";
           String link=node.getChildText("link").toString();
           XMLstr+="<link>"+link+"</link>";
           String desc=node.getChildText("description").toString();
           XMLstr+="<desc>"+desc+"</desc>";
           String pubDate=node.getChildText("pubDate").toString();
           XMLstr+="<pubDate>"+pubDate+"</pubDate>";           
        }
    }
catch(Exception e)
    {
    out.println(e);
    }
    XMLstr+="</FEED>";

但是,它无法正确解析。起初,它总是显示孩子的大小为0.请建议我在做什么错误,我怎么能纠正这一点。感谢。

2 个答案:

答案 0 :(得分:1)

XML具有以下结构

<rss>
  <channel>
    ...
    <item></item>
    <item></item>

E.g。 Element root = doc.getRootElement()将返回 rss 元素,该元素没有任何 item 子元素。

编辑:尝试以下行

List list = root.getChild("channel").getChildren("item");

答案 1 :(得分:0)

JDOM2使事情变得更容易......

public static void main(String[] args) throws MalformedURLException, JDOMException, IOException {
    final URL url = new URL("http://www.feedrinse.com/services/rinse/?rinsedurl=396ac3b0142bb6360003c8dbac4f8d47");
    SAXBuilder sbuilder = new SAXBuilder();
    Document doc = sbuilder.build(url);
    XPathExpression<Element> itemxp = XPathFactory.instance().compile("/rss/channel/item", Filters.element());

    Element feed = new Element("FEED");

    List<Element> items = itemxp.evaluate(doc);
    Element kidcount = new Element("children");
    kidcount.setText("" + items.size());
    feed.addContent(kidcount);
    for (Element item : items) {

        addItem(feed, item, "title");
        addItem(feed, item, "link");
        addItem(feed, item, "description");
        addItem(feed, item, "pubDate");
    }

    XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());

    //xout.output(doc, System.out);
    xout.output(feed, System.out);
}

private static void addItem(Element feed, Element item, String name) {
    Element emt = item.getChild(name);
    if (emt == null) {
        return;
    }
    feed.addContent(emt.clone());
}
相关问题