How can I read XML data using XPath in Java?

Asked 1 years ago, Updated 1 years ago, 135 views

I want to read XML data using XPath. So I want to get information without parsing XML documents.

What I want to do is:

I would like to use XPath to obtain XML documents online through URL and parse the data. I want to create two methods to do that. One is to get the child nodes of a particular node with attribute id, and the other is to search with the value of a particular child node.

<?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>

In the example above, you want to create a function that uses the @name attribute to search for specific elements, or to search for one element whose @name attribute is 'Javascript'.

I'd really appreciate it if you could solve my question^^

xpath java xml parsing

2022-09-21 22:55

1 Answers

You can add what you want to do between the following statements:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);

You can then enter the document (doc) defined in the code and the desired result type as input to invoke exp.evaluate() and cast the result object to that result type.

To give an additional explanation of the XPath expression,

The XPath expression for obtaining text data from the first URL element of 'PowerBuilder' is as follows.

/howto/topic[@name='PowerBuilder']/url/text()

The text data for the second URL element would be as follows.

/howto/topic[@name='PowerBuilder']/url[2]/text()

The command to obtain that data can be defined as follows.

expr.evaluate(doc, XPathConstants.STRING);

If you do not know the number of URL elements of a given node, it is recommended that you do the following. That is, XPathConstants.STRING is used to obtain a single string value, and XPathConstants.NODESET is used to read multiple values.

XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

If you repeat NodeList, you can read each URL text.


2022-09-21 22:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.