0

I am new to XML parsing and Java. I am trying to parse an xml using XPATH. The XML looks like this

<Root>
 <AL1>
  <AL1.1>1</AL1.1>
  <AL1.2>1</AL1.2>
  <AL1.3>
    <CX1.1>Bala</CX1.1>
  </AL1.1>
<AL1>
<AL1>
  <AL1.1>2</AL1.1>
  <AL1.2>1</AL1.2>
  <AL1.3>
    <CX1.1>Bala1</CX1.1>
  </AL1.1>
<AL1>
<AL1>
  <AL1.1>3</AL1.1>
  <AL1.2>1</AL1.2>
  <AL1.3>
    <CX1.1>Bala2</CX1.1>
  </AL1.1>
<AL1>
</Root>

I framed the XPATH like this for getting CX1.1 value /AL1/AL1.3/CX1.1/text(). So far I am able to get only the first occurrence if CX1.1.

XPathExpression expr = xpath.compile("/AL1/AL1.3/CX1.1/text()");
result = (String) expr.evaluate(doc.XPathConstants.STRING);

Could you guys please let me know of a way to get all the different values of CX1.1 in a List using XPATH. Any help is greatly appreciated. Thank you.

2 Answers 2

1

Firstly, the XML that you have provided is not well-formed, but once well-formed, I would do the following:

  String expression = "//AL1/AL1.3/CX1.1/text()";

        NodeList list = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);

        List<String> strings = new ArrayList<String>();

        for (int i = 0; i < list.getLength(); i++) {
            strings.add(list.item(i).toString());
        }

Which is to save the result of the xpath query in a NodeList and then iterate over it to save each value in a List<String> with a loop.

Sign up to request clarification or add additional context in comments.

Comments

0

First, fix your XML to be well-formed:

  • The AL1.3 start tags should not be closed with AL1.1 end tags, and
  • your AL1 start tags should be closed with AL1 end tags, not start tags.

Corrected XML:

<Root>
  <AL1>
    <AL1.1>1</AL1.1>
    <AL1.2>1</AL1.2>
    <AL1.3>
      <CX1.1>Bala</CX1.1>
    </AL1.3>
  </AL1>
  <AL1>
    <AL1.1>2</AL1.1>
    <AL1.2>1</AL1.2>
    <AL1.3>
      <CX1.1>Bala1</CX1.1>
    </AL1.3>
  </AL1>
  <AL1>
    <AL1.1>3</AL1.1>
    <AL1.2>1</AL1.2>
    <AL1.3>
      <CX1.1>Bala2</CX1.1>
    </AL1.3>
  </AL1>
</Root>

Corrected XPath

Then fix your XPath to take into account the Root element,

/Root/AL1/AL1.3/CX1.1/text()

or disregard the heritage of CX1.1 elements altogether:

//CX1.1/text()

Corrected Java

Finally, see Mary Grass's concurrent answer (+1) on how to fix your Java code so that the the given type is a XPathConstants.NODESET, not XPathConstants.STRING.

Comments

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.