Ashwini Pattanayak
Ashwini Pattanayak

Reputation: 21

How to read child XML using XPath in Java

The XML file is as :

Xml File

Code I have written:

List queryXmlUsingXpathAndReturnList(String xml, String xpathExpression) {

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance()

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder()

Document 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)

List returnElements = new ArrayList<>()

nodeList.each { n ->

returnElements.add(n.getTextContent())

}

When I am passing the xpath as:

/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter/StringElement

It returns all the values. But I want to return only the ListParameter values whose name="PackageTypeList".

For that I am using the xpath as:

/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter[@name='PackageTypeList']/StringElement

But it returns list as null.

Upvotes: 1

Views: 59

Answers (1)

JekO
JekO

Reputation: 78

I guess you miss "CommandResult" between "CommandResponseData" and "OperationResult" in your XPath-Expression.

Upvotes: 0

Related Questions