gpt4 book ai didi

java - 在java中解析嵌套的XML

转载 作者:行者123 更新时间:2023-12-01 13:13:17 25 4
gpt4 key购买 nike

我的 XML 如下

<Result>
<error><SubTask name="witbe" status="ERROR running Witbe" /></error>
<error><subtask name="VerifyDataServices" status="FAILURE" /></error>
.... multiple error tags

</Result>

我想检索错误标签下的全部内容,无论其中有什么标签。我试图用 XPath 解析它,但错误值却为 null

我正在使用的代码

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

if (null != inputStream)
{
Document doc = db.parse(inputStream);

XPath xPath = XPathFactory.newInstance().newXPath();

String errorTag = "/Result/error";

NodeList nodeList = (NodeList) xPath.compile(errorTag).evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}


}

知道如何解决这个问题吗?

最佳答案

if (nodeList.getLength() > 0) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.hasChildNodes()) {
Node childNode = node.getFirstChild();
System.out.println(childNode.getAttributes().getNamedItem("name")
+ " : " + childNode.getAttributes().getNamedItem("status"));
}
}
}

上面的代码将打印以下输出:

name="witbe" : status="ERROR running Witbe"name="VerifyDataServices" : status="FAILURE"

您需要这些值吗?

关于java - 在java中解析嵌套的XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com