Search code examples
xmlxpathxml-parsing

How to find element with specifc attribute value and element value


Please help with a xpath expression as explained below

   <A>
     <B x="P" Z="flag">2</B>
     <B x="Q" Z="nonflag"></B>
     <B x="R" Z="flag">3</B>
  </A>

How do i find out element A/Bwith Attribute Z as flag and element value as 2.. in this example the first <B x="P" Z="flag">2</B>


Solution

  • Attributes are preceded by @ in XPath. You can chain the predicates one after another:

    A/B[@Z="flag"][text()="2"]
    

    or use and:

    A/B[@Z="flag" and text()="2"]
    

    You can also say .="2" instead of text()="2", but it has a slightly different meaning if the element has subelements.

    (Tested in xsh).