How to Read Xml Using Xpath in Java

How to read XML using XPath in Java

You need something along the lines of this:

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>);

Then you call expr.evaluate() passing in the document defined in that code and the return type you are expecting, and cast the result to the object type of the result.

If you need help with a specific XPath expressions, you should probably ask it as separate questions (unless that was your question in the first place here - I understood your question to be how to use the API in Java).

Edit: (Response to comment): This XPath expression will get you the text of the first URL element under PowerBuilder:

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

This will get you the second:

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

You get that with this code:

expr.evaluate(doc, XPathConstants.STRING);

If you don't know how many URLs are in a given node, then you should rather do something like this:

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

And then loop over the NodeList.

How to parse a complex XML using Xpath

I am using the below method :

public static String inputXmlXPathParser(String inputXml){


//==================================================X-Path Parser =============================================================//

String transactionName = StringUtils.EMPTY;

try {

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource( new StringReader(inputXml)));
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expression = xpath.compile("/Service/Inquiry/InquiryType/text()");
NodeList xpathNodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
System.out.println("InquiryType is : " +xpathNodeList.item(0));

} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return transactionName;

}

How to read xml using XPATH in Java

Try the following xpaths

 //content[@xsi:type='mpnG2:PaymentReq']/bankId or  

//content[@xsi:type='mpnG2:PaymentReq'][1]/bankId or

//bankId or

//bankId[1]

I've tested the xpaths for your xml in this online Xml Xpath tester

Using XPATH to retrieve values from repeating XML nodes

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.

Read value from XML String using XPATH Java

Try this :)

 String xmlDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Body>This is my content</Body>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String value = builder.parse(new InputSource(new ByteArrayInputStream(xmlDoc.getBytes())))
.getDocumentElement().getTextContent();

It returns value inside <Body> tag - "This is my content".

How to get a part of xml using xpath in java

Load the XML and find the nodes you are looking for...

DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document d = b.parse(...);

// Find all nodes with the attribute of type equal to `t1`
// You could use //*/a[@type='t1'] if you wanted to narrow it down
// This find ALL matches through out the document...
String expression = "//*[@type='t1']";
XPath xPath = XPathFactory.newInstance().newXPath();
Object result = xPath.compile(expression).evaluate(d, XPathConstants.NODESET);

NodeList nodes = (NodeList) result;

Create a new Document....

Document d2 = b.newDocument();
Element root = d2.createElement("root");
d2.appendChild(root);

Add the nodes from the first to the second...

for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
d2.adoptNode(node);
root.appendChild(node);
}

Which should result in...

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<a type="t1">
<property name="data" value="val1"/>
</a>
<a type="t1">
<property name="data" value="val2"/>
</a>
</root>

Parsing XML with XPath in Java

This link has everything you need. In shorts:

 public static void main(String[] args) 
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {

DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//person/*/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}


Related Topics



Leave a reply



Submit