Search code examples
xpathnormalize-space

Query Xpath match first string instead of contain text()


I have a xml file like this:

<Doc> A0B100 </Doc>
<Doc> A0B101 </Doc>
<Doc> B1A100 </Doc>
<Doc> B1A101 </Doc>

I use xpath query to select value of node that contain "B1" my code :

$txtSearch = "B1";
$titles = $xpath->query("Doc[contains(text(),\"$txtSearch\")]");

It returned all 4 value :

A0B100 
A0B101 
B1A100 
B1A101 

But I only want the contain text() to match first string that the result I expected is

B1A100 
B1A101 

How can I do that?


Solution

  • use this xpath

    Doc[starts-with(normalize-space(text()),\"$txtSearch\")]
    

    added normalize-space() to trim spaces on your sample xml