Reputation: 5850
Using XPath.
I have this doc:
<?xml version="1.0"?>
<root>
<items>
<item1>
<tag1>1</tag1>
<tag2>DFGGFDGF</tag2>
<tag3>3</tag3>
</item1>
<item2>
<tag1>DFGD</tag1>
<tag2>SDFSDFFSD</tag2>
<tag3>SDFSFDFS</tag3>
</item2>
</items>
</root>
I want to get the tags names of the item1
element.
Now i use this to get the tags value:
XPathExpression expr = xpath.compile("//"+ node_name +"/*/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());
}
How do i get the tags names: tag1
, tag2
, tag3
?
Upvotes: 0
Views: 110
Reputation: 17445
First of all, don't use text() at the end of your XQuery. You need the nodes themselves. Second, don't take the node value, you need the node name instead.
XPathExpression expr = xpath.compile("//"+ node_name +"/*");
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).getNodeName());
}
Upvotes: 1
Reputation: 725
Give like this
xpath.compile("//"+ node_name +"/*")
.......................
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
Upvotes: 2
Reputation: 17779
Try org.w3c.dom.Node#getNodeName()
to get the name of the node.
Also see "org.w3c.dom.Node"
Upvotes: 0