Search code examples
xpathxmllint

How to select all nodes using xmllint where node on same level has certain value?


Consider the following example.xml file

<all>
  <item>
    <name>foo</name>
    <value>5</value>
    <readonly>true</readonly>
  </item>
  <item>
    <name>boo</name>
    <value>2</value>
    <readonly>false</readonly>
  </item>
  <item>
    <name>bar</name>
    <value>9</value>
    <readonly>true</readonly>
  </item>
</all>

I would like to list foo and bar because they are readonly items. This didn't work out for me:

cat example.xml | xmllint --xpath "all/item[readonly/text() = "true"]/name" -

I received:

XPath set is empty

Solution

  • You can try using this xpath :

    /all/item[readonly='true']/name
    

    Your initial xpath also looks good given the XML posted in question as input, only you may need to change double quotes with single quotes in the xpath parameter value :

    --xpath "all/item[readonly/text() = 'true']/name"