How to Use XPath to Select an XML Node That Partially Matches a Value?

To select a node that partially matches a value, you can use the xpath contains() function, like so:

//root/node[contains(text(), "needle")]

For example, let's suppose you have the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<customers>
    <customer>
        <name>John Doe</name>
        <age>24</age>
        <address>Gartenstraße 1, 10115 Berlin, Germany</address>
    </customer>
    <customer>
        <name>Jane Doe</name>
        <age>29</age>
        <address>Bahnhofstrasse 1, 8001 Zürich, Switzerland</address>
    </customer>
    <customer>
        <name>Bruce Wayne</name>
        <age>39</age>
        <address>123 Park Way, CA 92120, USA</address>
    </customer>
</customers>

To select all customers with "Doe" in the name, you would do the following:

//customers/customer/name[contains(text(), "Doe")]

This would result in the following matches:

<name>John Doe</name>
<name>Jane Doe</name>

To match values with special characters (for example, in foreign languages such as German), you can specify a collation as the third (optional) argument to the contains() function.

Consider, for example, the following, where the specified collation equates "ss" to the (German) character "ß" ("sharp-s"):

//customers/customer/address[contains(text(), "straße", "http://www.w3.org/2013/collation/UCA?lang=de;strength=primary")]

This is the same as doing the following:

//customers/customer/address[contains(text(), "strasse", "http://www.w3.org/2013/collation/UCA?lang=de;strength=primary")]

Both of the expressions would result in the following matches:

<address>Gartenstraße 1, 10115 Berlin, Germany</address>
<address>Bahnhofstrasse 1, 8001 Zürich, Switzerland</address>

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.