0

I have written code that enables me to a subsection of an xml request based on a given XPath, however, it is only the value between the tags that are returned and not the tags.

I want both values and elements to be returned based on a given xpath.

For example, in this xml:

?xml version="1.0"?>
<company>
  <staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>
  <staff2>
    <name>mary</name>
    <phone>4655556433</phone>
    <email>gmail2</email>
    <area>area2</area>
    <city>city2</city>
  </staff2>
  <staff3>
    <name>furvi</name>
    <phone>4655433</phone>
    <email>gmail3</email>
    <area>area3</area>
    <city>city3</city>
  </staff3>
</company>

my XPath would only return the value of the first staff element i.e.

John
465456433
gmail1
area1
city1

It does not return the tags associated to it i.e, it should return the following:

<staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>

Here is my code:

      InputSource inputSource = new InputSource(new StringReader(xmlString));
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            String RecordCategory;

        Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputSource);

        // Create XPathFactory object
        XPathFactory xpathFactory = XPathFactory.newInstance();

        // Create XPath object
        XPath xpath = xpathFactory.newXPath();

        System.out.println("TESTING XPATH");

        xpath.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
...
               });
    XPathExpression expr = xpath.compile("//staff1[1]");




        Staff1 = (String) expr.evaluate(doc,XPathConstants.STRING);
        System.out.println("staff1: " + staff1);

Anyone have any idea on what I could do to resolve this issue?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
MoStack
  • 1
  • 1

1 Answers1

0

Your Java call to XPathExpression.evaluation() is returning the string value of the node selected by your XPath expression. If you instead want to return the node selected by your XPath expression, change

Staff1 = (String) expr.evaluate(doc, XPathConstants.STRING);

to

Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);

See this answer for how to pretty print node.

kjhughes
  • 106,133
  • 27
  • 181
  • 240