0

嗨,我有一个如下所示的 xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A>
    <B>
        <X1>
            <Name>ZZZsaqw</Name>
        </X1>
        <X1>
            <Name>ZZZsdasda</Name>
        </X1>
        <X1>
            <Name>ZZZsdsd</Name>
        </X1>
        <S>17000</S>
        <U>18000</U>
        <V>17000</V>
    <B>
    <C>
        <X1>
            <Name>ZZZasqw</Name>
        </X1>
        <X1>
            <Name>ZZZsdsd</Name>
        </X1>
        <X1>
            <Name>ZZ</Name>
        </X1>
        <S>17000</S>
        <U>18000</U>
        <V>17000</V>
    <C>
    <D>
        <X1>
            <Name>ZZZx</Name>
        </X1>
        <X1>
            <Name>ZZZzz</Name>
        </X1>
        <X1>
            <Name>ZZZsaa</Name>
        </X1>
        <S>17000</S>
        <U>18000</U>
        <V>17000</V>
    </D>
<A>

我对 X1 标签感兴趣。我需要阅读它们各自的父标签,它们可以是 B、C 或 D。所以有时我只对属于 B 有时属于 C 的 X1 标签感兴趣。如何做到这一点?我使用了下面显示的 DOM 解析器,但是当我计算它们时,它显示计数为 9,而应该是 3。请帮助我怎么做。

        NodeList plist = doc.getElementsByTagName("A");
        System.out.println("The length of A is pList is:"+plist.getLength());
        //get the contents of the A
        for (int temp = 0; temp < plist.getLength(); temp++)
        {
            Node nNode = plist.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE)
            {
                //Element eElement = (Element) nNode;

                NodeList typicalCriticalPath = doc.getElementsByTagName("B");
                System.out.println("The length of B is:"+typicalCriticalPath.getLength());

                //get the contents of the typical critical path
                for(int temp1 = 0; temp1<typicalCriticalPath.getLength();temp1++)
                {
                    Node typCriticalPathNode = typicalCriticalPath.item(temp);
                    if (typCriticalPathNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element ele = (Element) typCriticalPathNode;
                        NodeList planItemSection = doc.getElementsByTagName("X1");
                        System.out.println("The length of X1 is:"+planItemSection.getLength());
                    }

                }

            }
        }
 //The output for this is like this-
 //The length of A is pList is:1
 //The length of B is:1
 //The length of X1 is:9

有人可以指出我哪里出错了吗?要做什么才能让我只能获得父标签的标签。

谢谢!

4

1 回答 1

4

NodeList planItemSection = doc.getElementsByTagName("X1");

这将是文档中的所有 X1。

我想你想要

NodeList planItemSection = ele.getElementsByTagName("X1");

,ele父元素在哪里。

您可能还想查看 XPath 以获取此类查询。

于 2012-09-20T23:28:27.723 回答