gpt4 book ai didi

java - java读取xml标签的方法

转载 作者:行者123 更新时间:2023-12-01 19:00:14 27 4
gpt4 key购买 nike

嗨,我有一个如下所示的 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 的 X1 标签感兴趣,有时属于 C。如何做到这一点?我使用了如下所示的 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

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

谢谢!

最佳答案

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

这就是文档中的所有 X1。

我想你想要

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

,其中 ele 是父元素。

您可能还想研究 XPath 来查找此类查询。

关于java - java读取xml标签的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522355/

27 4 0