0

I have an xml as follow:

<root>

<outer>
<name>abc</name>
<age>20</age>
</outer>

<outer>
<name>def</name>
<age>30</age>
</outer>

<outer>
<name>ghi</name>
<age>40</age>
</outer>


</root>

I want to fetch the value of age tag for a given value of name tag?

One way is that I can prepare a map of name to age by parsing this xml using Document interface.

But is there any api that I can just call for Document interface in which I can say fetch element where name is say,ghi, and then i can iterate all atributes to get age attribute or any other simple way to get age where name value is,say ghi?

2
  • I'm not familiar with java XML parsing, but should be trivial with XPath Commented Feb 21, 2022 at 13:11
  • I have xml available in org.w3c.dom.Document object Commented Feb 21, 2022 at 13:12

2 Answers 2

2

Turns out java does come with an XPath evaluator in the javax.xml.xpath package, which makes this trivial:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

public class Demo {
    public static void main(String[] args) throws Exception {
        String name = "ghi";
        // XPath expression to find an outer tag with a given name tag
        // and return its age tag
        String expression = String.format("/root/outer[name='%s']/age", name);
        
        // Parse an XML document
        DocumentBuilder builder
            = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new File("example.xml"));

        // Get an XPath object and evaluate the expression
        XPath xpath = XPathFactory.newInstance().newXPath();
        int age = xpath.evaluateExpression(expression, document, Integer.class);

        System.out.println(name + " is " + age + " years old");       
    }
}

Example use:

$ java Demo.java
ghi is 40 years old
Sign up to request clarification or add additional context in comments.

2 Comments

thanks,i will try and update
both solutions worked fine
1

XPath is a very expressive API that can be used to select the elements.

/root/outer[name = "ghi"]/age

This article https://www.baeldung.com/java-xpath provides a pretty good overview and explanation of how to apply an XPath in Java.

Adjusting one of their code samples for your XPath:

String name = "ghe";

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(this.getFile());
XPath xPath = XPathFactory.newInstance().newXPath();

String expression = "/root/outer[name=" + "'" + name + "'" + "]/age";
node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

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.