Reputation: 11
I need to get some values from this xml document:
<node id="A." label="General Literature">
<isComposedBy>
<node id="A.0" label="GENERAL">
<isComposedBy>
<node label="Biographies/autobiographies"/>
<node label="Conference proceedings"/>
<node label="General literary works (e.g., fiction, plays)"/>
</isComposedBy>
</node>
<node id="A.1" label="INTRODUCTORY AND SURVEY"/>
<node id="A.2" label="REFERENCE (e.g., dictionaries, encyclopedias, glossaries)"/>
<node id="A.m" label="MISCELLANEOUS"/>
</isComposedBy>
</node>
In Java how can i select only the nodes with the attributes id
and label
and then get the values of those attributes?
I've tried with XPath using this expression:
XPathExpression expr = path.compile("//*/@id | /@label");
But this is not returning what i want.
Upvotes: 0
Views: 153
Reputation: 72844
Using //node[@id and @label]
will get all node
elements having id
and label
attributes. Then you would need to loop over the nodes to get their attribute values. An example using DOM:
for(int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
NamedNodeMap attributes = node.getAttributes();
System.out.println(attributes.getNamedItem("id").getTextContent());
System.out.println(attributes.getNamedItem("label").getTextContent());
}
Upvotes: 1
Reputation: 167426
Use XPathExpression expr = path.compile("//*[@id and @label]/(@id | /@label)");
with XPath 2.0 or XPathExpression expr = path.compile("//*[@id and @label]/@id | //*[@id and @label]/@label");
with XPath 1.0.
Upvotes: 1
Reputation: 530
Try this way:
XPathExpression expr = path.compile("//*/*[@id and @label]");
Upvotes: 0