0

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と表示されます。私が行っている間違いと、それを修正するにはどうすればよいかを提案してください。ありがとう。

4

2 に答える 2

1

XMLの構造は次のとおりです。

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

たとえば、アイテムの子を持たないrssElement root = doc.getRootElement()要素を返します。

編集:次の行を試してください

List list = root.getChild("channel").getChildren("item");
于 2012-05-05T14:01:22.840 に答える
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());
}
于 2012-05-05T17:06:01.773 に答える