簡體   English   中英

如何使用 Java 中的 XPath 讀取子 XML

[英]How to read child XML using XPath in Java

XML 文件如下:

Xml 文件

我寫的代碼:

列表查詢XmlUsingXpathAndReturnList(字符串xml,字符串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

但它返回列表為 null。

我猜你錯過了 XPath 表達式中“CommandResponseData”和“OperationResult”之間的“CommandResult”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM