How to use XPath to filter elements by TextContent? get parent by axis?
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-06-11T01:29:12Z
Indexed on
2010/06/11
1:32 UTC
Read the original article
Hit count: 414
Hi all:
I've found a similar question on SO, however, that seems not exactly what I wanna achieve:
Say, this is a sample XML file:
<root>
<item>
<id isInStock="true">10001</id>
<category>Loose Balloon</category>
</item>
<item>
<id isInStock="true">10001</id>
<category>Bouquet Balloon</category>
</item>
<item>
<id isInStock="true">10001</id>
<category>Loose Balloon</category>
</item>
</root>
If I wanna get a "filtered" subset of the item elements from this XML, how could I use an XPath expression to directly address that?
XPathExpression expr = xpath.compile("/root/item/category/text()");
I now know this would evaluate to be the collection of all the TextContent from the categories, however, that means I have to use a collection to store the values, then iterate, then go back to grab other related info such as the item id again.
Another question is : how could I refer to the parent node properly?
Say, this xpath expression would get me the collection of all the id nodes, right? But what I want is the collection of item nodes:
XPathExpression expr = xpath.compile("/root/item/id[@isInStock='true']");
I know I should use the "parent" axis to refer to that, but I just cannot make it right...
Is there a better way of doing this sort of thing? Learning the w3cschools tutorials now...
Sorry I am new to XPath in Java, and thanks a lot in advance.
© Stack Overflow or respective owner