Marouane Gazanayi
Marouane Gazanayi

Reputation: 5193

Check if a node exist in XML using XPath in Java

I have different forms of XML that I must analyse,

<AMDI>
...
<MI>
</MI>
</AMDI>

or

<AMDI>
...
<AD>
</AD>
</AMDI>

So I want to build an XPath query depending of the type of the node (if it's an MI : XML_ITEMS = "//MI/DL/D", if it's an AD : XML_ITEMS = "//AD/DL/D") I'm working with DocumentBuilder and XPathExpression. Thnx for the help :)

Upvotes: 0

Views: 2766

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243579

In XPath 1.0:

//MI/DL/D  |   //AD/DL/D

This is not syntactically legal in XPath 1.0:

//(MI|AD)/DL/D

But you may use it in case you have an XPath 2.0 engine.

Upvotes: 2

Marouane Gazanayi
Marouane Gazanayi

Reputation: 5193

You can also list the different nodes like this :

Node node = doc.getDocumentElement();
NodeList type = node.getChildNodes();
for(int i=0; i<nodes.getLength();i++)
     System.out.println(type.item(i).getNodeName();

And choose the write node :) Thanx a lot

Upvotes: 2

Related Questions