首页 > 解决方案 > 如何在 Java 中使用 XPath 读取子 XML

问题描述

XML 文件如下:

xml文件

我写的代码:

列出 queryXmlUsingXpathAndReturnList(String xml, String xpathExpression) {

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance()

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder()

文档 doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))

doc.getDocumentElement().normalize()

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

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

列表 returnElements = new ArrayList<>()

nodeList.each { n ->

returnElements.add(n.getTextContent())

}

当我将 xpath 传递为:

/信封/正文/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter/StringElement

它返回所有值。但我只想返回 name="PackageTypeList" 的 ListParameter 值。

为此,我将 xpath 用作:

/信封/正文/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter[@name='PackageTypeList']/StringElement

但它返回列表为空。

标签: javaxmlxpathsoapxml-parsing

解决方案


我猜你错过了 XPath 表达式中“CommandResponseData”和“OperationResult”之间的“CommandResult”。


推荐阅读