解析并比较XML标记文本以获取兄弟姐妹

时间:2012-12-19 06:16:19

标签: java android xml-parsing

我正在解析看起来像这样的NOAA XML:

<time-layout time-coordinate="local" summarization="12hourly">
<layout-key>k-p12h-n14-1</layout-key>
<start-valid-time period-name="Tonight">2012-12-18T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Wednesday">2012-12-19T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Wednesday Night">2012-12-19T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Thursday">2012-12-20T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Thursday Night">2012-12-20T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Friday">2012-12-21T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Friday Night">2012-12-21T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Saturday">2012-12-22T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Saturday Night">2012-12-22T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Sunday">2012-12-23T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Sunday Night">2012-12-23T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Monday">2012-12-24T06:00:00-08:00</start-valid-time>
<start-valid-time period-name="Monday Night">2012-12-24T18:00:00-08:00</start-valid-time>
<start-valid-time period-name="Christmas Day">2012-12-25T06:00:00-08:00</start-valid-time>
</time-layout>  

文档中还有其他标记,但我想要 k-p12h-n14-1 标记。

如何仅为k-p12h-n14-1后面的句点名称获取period-name =“*”?

这是FULL XML FILE EXAMPLE

我试图用以下方法搞清楚:

List<XmlDom> wxday = xml.tags("time-layout","time-coordinate","summarization");
String wxd = wxday.child("layout-key");
String wxdd = wxday.equals("k-p12h-n14-1");
kind of lost.... 

感谢您的任何想法。

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码:

    File fXmlFile = new File("MapClick.php.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    Element rootElement = doc.getDocumentElement();

    NodeList nodeList = rootElement.getElementsByTagName("layout-key");
    int size = nodeList.getLength();

    for (int i = 0; i < size; i++) {
        Node currentNode = nodeList.item(i);

        if (currentNode.getTextContent().trim().equals("k-p12h-n14-1")) {
            while (currentNode.getNextSibling() != null) {
                currentNode = currentNode.getNextSibling();

                if (currentNode.getNodeName().equals("start-valid-time")) {
                    System.out.println(((Element)currentNode).getAttribute("period-name"));
                }
            }
        }
    }