XPath wildcards and contains() function usage

21,738

Try this:

/doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name

Here is a working example implemented in Javascript to take advantage of StackOverflow's Runnable Code Snippets

function fu(path){
  var output = "";
  var results =  document.evaluate(path, document, null, XPathResult.ANY_TYPE  , null);
  while(nextResult = results.iterateNext()){ output += nextResult.outerHTML + "\n"; }
  return output;
}

document.body.innerText = fu('//doc/Test[contains(Name, "Pre") and Type="Known"]/Data/Name');
<doc>  
 <Test>
   <Name>1 Pre Histoy</Name>
   <Type>Known</Type>
   <Data>
      <Name>Dinasor</Name>
      <Name>Fish</Name>
  </Data>
  </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>Known</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>

  <Test>
    <Name>1 Post Histoy</Name>
    <Type>UNKNOWN</Type>
    <Data>
      <Name>Human</Name>
      <Name>Dog</Name>
    </Data>
 </Test>  

  </doc>
Share:
21,738

Related videos on Youtube

EMBEDONIX
Author by

EMBEDONIX

Protecting yourself against thrown exceptions, considered as a defensive programming practice.

Updated on February 24, 2020

Comments

  • EMBEDONIX
    EMBEDONIX over 3 years

    I have a problem using XPath and contains function. Imagine the XML example below:

       <doc>  
         <Test>
           <Name>1 Pre Histoy</Name>
           <Type>Known</Type>
           <Data>
              <Name>Dinasor</Name>
              <Name>Fish</Name>
          </Data>
          </Test>
    
          <Test>
            <Name>1 Post Histoy</Name>
            <Type>Known</Type>
            <Data>
              <Name>Human</Name>
              <Name>Dog</Name>
            </Data>
         </Test>
    
          <Test>
            <Name>1 Post Histoy</Name>
            <Type>UNKNOWN</Type>
            <Data>
              <Name>Human</Name>
              <Name>Dog</Name>
            </Data>
         </Test>  
    
      </doc>
    

    So what I want to do is returning all <Name> texts within <Data> node, with following criteria:

    1. doc//Test/Name should contain "Pre" text

    2. doc//Test/Type should be "Known"

    What I need is a query like this but so far I couldn't manage it

    /doc//Test[Name contains(.,'Pre') and Type='Known']/data//Name
    

    Any help and tips will be appreciated.

  • BoltClock
    BoltClock over 12 years
    @Jon: Thanks! This is my second XPath answer ever :)
  • Waihon Yew
    Waihon Yew over 12 years
    Clearly you pick it up faster than I do ;)
  • Günay Gültekin
    Günay Gültekin over 10 years
    I have tested for the same reason, it was worked.Thanks! Mine is /PlaceSearchResponse/result[contains(name,'Bimeks')]/geometr‌​y

Related