什么样的循环用于从xml输出标题和描述

时间:2014-09-05 17:11:26

标签: java xml

我有一些代码从网络上读取xml,我从NodeList获取了标题和描述:

        DocumentBuilderFactory factory = 
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("http://services.explorecalifornia.org/rss/tours.php");

        NodeList titleNode = doc.getElementsByTagName("title");
        NodeList summaryNode = doc.getElementsByTagName("description");

我想循环遍历它们并获得像

这样的输出
  

标题

     

描述

     

标题

     

描写的特征

如果循环可行,我无法理解,因为我使用嵌套循环它为每个外循环循环内循环任何其他类型循环的建议

以下是XML的示例:(来自http://services.explorecalifornia.org/rss/tours.php

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Explore California Tours</title>
    <description>Explore Our World Your Way</description>
    <link>http://www.explorecalifornia.org</link>
    <copyright>Copyright (c) 2011 lynda.com</copyright>
    <item>
      <title>2 Days Adrift the Salton Sea</title>
      <link>http://www.explorecalifornia.org/tour.php?id=14</link>
      <description>The Salton Sea is saltier than the Pacific, an unusual feat for inland body of water. And even though its salinity has risen over the years, due in part to lack of outflows and pollution from agricultural runoff, it has attracted a small, but dedicated population. The sea itself offers recreational opportunities including boating, camping, off-roading, hiking, use of personal watercraft, photography and bird watching. The sea has been termed a "crown jewel of avian biodiversity," being a major resting stop on the Pacific Flyway, a migratory path for birds. 2 Days Adrift the Salton Sea includes two nights accommodations at the Bombay Beach Inn, boat rental at the Salton City Harbor, and a guided fishing tour.</description>
      <category>From Desert to Sea</category>
    </item>
    <item>
      <title>A Week of Wine</title>
      <link>http://www.explorecalifornia.org/tour.php?id=26</link>
      <description>Immerse yourself in the culture and lifestyle of a California winery. Spend 5 days in your private guest villa at the Stockbridge Winery, located in scenic Sonoma. You'll spend your days wandering the vineyards, touring the presses and cellars, and assisting staff in making America's favorite wine. Enjoy Tuscan-style meals served al fresco, overlooking the gorgeous countryside. Day trips include dinner in Sausalito, hiking in the redwood forests, and lunch in downtown San Francisco.</description>
      <category>Taste of California</category>
    </item>
    <!-- ...and so on... -->
  </channel>
</rss>

3 个答案:

答案 0 :(得分:1)

如果有相同数量的标题和描述,并且您想要并行输出它们,那么您只需要一个简单的循环:

int i;
for (i = 0; i < titleNodes.length; ++i) {
    // output titleNodes[i] here
    // output descriptionNodes[i] here
}

但更可能的是,有一个容器元素包含其中的两个元素元素,并且最好循环遍历容器元素,然后在每个容器元素中查找标题和描述。

编辑 (一旦发布了XML):例如,在这种情况下,您可能希望循环遍历item元素,然后检索它们循环时的标题和描述:

for (Element element : doc.getElementsByTagName("item")) {
    // Output element.getElementsByTagName("title").item(0) here
    // Output element.getElementsByTagName("description").item(0) here
}

根据您使用的DOM库,您可以使用element.querySelector("title")而不是element.getElementsByTagName("title").item(0)(对于文档也是如此)。


请注意,我更改了变量的名称(使其成为复数,例如titleNodes而不是titleNode),因为它们是列表,而不是单个节点。

答案 1 :(得分:1)

你走了:

NodeList itemNodes = doc.getElementsByTagName("item");
for (int i =0; i < itemNodes.getLength(); i++) {
    Element itemElement = (Element) itemNodes.item(i);
    String title = itemElement.getElementsByTagName("title").item(0).getTextContent();
    String description = itemElement.getElementsByTagName("description").item(0).getTextContent();

}

基本上,您需要为“标题”和“描述”获取父节点。然后在找到的节点的祖先中搜索。

答案 2 :(得分:0)

你可以这样做:

NodeList itemNode = doc.getElementsByTagName("item");
for (int i = 0; i < itemNode.getLength(); i++) {
  Element itemEle = (Element)itemNode.item(i);
  // You chould check if there is a title/description element, I'm skipping this for brevity
  Element titleEle = (Element)itemEle.getElementsByTagName("title").item(0);
  Element descrEle = (Element)itemEle.getElementsByTagName("description").item(0);
  // Output them, now you're sure you are in the same pair
}