1

I have the following problem. Im using Xpath to extract the value from XML file using JAVA program

<place> 
<native name= "AAAAAA" />
<native name= "BBBBBB" />
<native name= "CCCCCC" />
<native name= "DDDDDD" />
<native name= "EEEEEE" />
</place>

Above is my partial XML file. Im using the following Xpath

/root/place/native/@name
/root/home
/root/xxxxxx

and i want my result to be like this

AAAAAA|BBBBBBB|CCCCCCC|DDDDDDD|EEEEEEEˆevergreenˆvaluesˆexample

How can i do this . Can any one help me

for (String temp : XpathValue) {
              TempFlat = xPath1.compile(temp).evaluate(xmlDocument);
                        TempFlat1 = TempFlat.replaceAll("\\s+", " ");
                        value1.append(TempFlat1);
                        value1.append((char)"ˆ");

1 Answer 1

3

XPathExpression#evalute will return a NodeList if you use XPathConstants.NODESET.

Once you have the NodeList, you will need to iterate the list and populate your array...

NodeList nodeList = (NodeList)xPath1.compile("/place/native[@name]").evaluate(xmlDocument, XPathConstants.NODESET);
String[] results = new String[nodeList.getLength()];
for (int index = 0; index < nodeList.getLength(); index++) {
    Node node = nodeList.item(index);
    String name = node.getAttributes().getNamedItem("name");
    results[index] = name;
}
Sign up to request clarification or add additional context in comments.

4 Comments

The problem is (from my testing), evalute(xmlDocument) is only return the first match, where as the example I posted returns all of them...
Okay , Can you kindly provide me the link to refer or more example
I added one more line (that gets the NodeList from the expession)
How XPath Works, XPath W3School. I've not read all the way through it, but this might be useful Java XPath Tutorial: How To Parse XML File Using XPath In Java

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.