How to use XPath to filter TextContent elements? get parent axis?

I found a similar question about SO , however, it seems not quite what I want to achieve:

Let's say this is an example of an 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 want to get a “filtered” subset of element elements from this XML, how can I use an XPath expression to access this directly?

XPathExpression expr = xpath.compile("/root/item/category/text()");

Now I know that this will evaluate as a collection of the entire TextContent from the categories, however this means that I have to use the collection to store the values ​​and then iterate and then go back to capture other related information, such as the Item ID again.

Another question: how can I access the parent node correctly?

, xpath , ? , , :

XPathExpression expr = xpath.compile("/root/item/id[@isInStock='true']");

, "" , , ...

? w3cschools ...

, XPath Java, .

+3
3

"" XML, XPath ?

XPath:

/*/item[id/@isInStock='true']/category/text()

XPath text- node <category> <item>, isInStock, id 'true' (id ), XML-.

: node?

parent::node()

..

+6

, , id (s)

XPathExpression expr = xpath.compile("/root/item/id[@isInStock='true']/../text()");

, NodeList, item ( ), .

+1

Java

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;

The following XPath expression can be used to filter an element by the contents of the text.

**String xPathString = "/root/item/category[text()='Bouquet Balloon']";** 

XPath xPath = XPathFactory.newInstance().newXPath();     
XPathExpression xPathExpression = xPath.compile(xPathString);

Get the result obtained for the required type,

Object result = xPathExpression.evaluate(getDrugBankXMLDoc(), XPathConstants.NODE);

Get the parent of the selected Node (import org.w3c.dom.Node;),

Node baloon = (Node)result;
if (baloon != null)
{
     baloon = baloon.getParentNode();
}
+1
source

Source: https://habr.com/ru/post/1749506/


All Articles