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?
CodePudding user response:
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);
CodePudding user response:
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