java - 如何在 Java 中使用 XPath 读取子 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
但它返回列表为空。
解决方案
我猜你错过了 XPath 表达式中“CommandResponseData”和“OperationResult”之间的“CommandResult”。
推荐阅读
- macos - Pyautogui 图像识别功能在 m1 Mac 上无法正常工作
- react-native - 如何使用 React Native 显示视频
- javascript - 未处理的承诺拒绝nodejs
- javascript - Chrome 计时器节流和@microsoft/signalr 问题
- sql - 如何编写有效的查询来检索附加到 ID 的电话号码?
- html - 表内中心 TH
- javascript - 如何循环然后保存产品?
- javascript - 使用正则表达式提取字符串
- timezone - 对话流程:今天和明天需要返回日期和时间 - 只返回中午的日期
- json - MappedListIterable
' 不是类型 'List 的子类型 '