我有一个函数,我想循环遍历 xml 并提取某些标签。
我的 xml 看起来像这样:
<Report_Data>
<Report_Entry>
<Company>Test</Company>
<Name>Test Name</Name>
<Division>Test Division</Division>
</Report_Entry>
<Report_Entry>
<Company>Test 2</Company>
<Name>Test Name 2</Name>
<Division>Test Division 2</Division>
</Report_Entry>
<Report_Entry>
<Company>Test 3</Company>
<Name>Test Name 3</Name>
<Division>Test Division 3</Division>
</Report_Entry>
</Report_Data>
这是我要循环的代码:
String comp, name, div, nodeName, NodeValue;
Node node;
try
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
InputSource source = new InputSource(new StringReader(coaFULL));
Document doc2 = (Document) xpath.evaluate("/", source, XPathConstants.NODE);
NodeList nodeList = (NodeList) xpath.compile("/Report_Data/Report_Entry").evaluate(doc2, XPathConstants.NODESET);
System.out.println("NODE LIST LENGTH =" + nodeList.getLength());
String nodeName, nodeValue = "";
Node node;
for(int i = 0; i < nodeList.getLength(); i++)
{
node = nodeList.item(i);
node = nodeList.item(i).getFirstChild();
nodeName = node.getNodeName();
nodeValue = node.getChildNodes().item( 0 ).getNodeValue();
if(nodeName.equals("Company"))
{
comp = nodeValue;
}
else if( nodeName.equals("Name"))
{
name = nodeValue;
}
else if(nodeName.equals("Division"))
{
div = nodeValue;
}
System.out.println("COMPANY = " + comp);
System.out.println("NAME = " + name);
System.out.println("DIVISION = " + div);
}
当我运行代码时,只有第一个值(公司)获得实际值,其他所有值都是空白。我还尝试在每个 if 语句内添加 node = nodeList.item(i).getNextSibling();
以获取下一个节点,但这不起作用。
我的nodeList中确实有项目,超过1000个。这个语句有问题吗:NodeList nodeList = (NodeList) xpath.compile("/Report_Data/Report_Entry").evaluate(doc2, XPathConstants.NODESET );
?
应该是:NodeList nodeList = (NodeList) xpath.compile("/Report_Data/Report_Entry/*").evaluate(doc2, XPathConstants.NODESET);
我在末尾尝试了 /*
,但这导致 nodeList 中包含每个节点。我想确保当我获取 Report_Entry 节点时,我将字符串变量设置为彼此对应的正确值。
================================================== ===========
解决方案:这很丑陋,但我的解决方案是只进行一个循环并使用具有硬编码值的第二个子节点列表:
for(int i = 0; i < nodeList.getLength(); i++)
{
node = nodeList.item(i);
tempList = node.getChildNodes();
System.out.println("TEMP LIST LENGTH =" + tempList.getLength());
comp = tempList.item(0).getTextContent();
name = tempList.item(1).getTextContent();
div = tempList.item(2).getTextContent();
}
感谢@hage 的帮助。
最佳答案
也许是因为您的节点
只是第一个子节点?
node = nodeList.item(i);
node = nodeList.item(i).getFirstChild();
我猜 nodeList.item(i)
会给您 Report_Entry
,它们的第一个子项是 Company
。
您需要循环 Company
条目的所有子项
编辑(关于您的编辑):
tempList.item(x)
是公司
、名称
,然后是部门
。当您获得该节点的第一个子节点时,您就位于文本节点(实际内容)。由于您尝试获取此节点的名称,因此您将获得 #text
输出 ( see this )。
要获取节点的名称和值,请尝试此操作(未经测试)
nodeName = tempList.item(x).getNodeName();
nodeValue = tempList.item(x).getTextContent();
关于java - 使用 XPath 循环 XML 字符串 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21553798/