简体   繁体   中英

creaing xpath expression for following xml

I'm extremely new to XPath, and I'm in the process of creating a XPath expression for retrieving multiple elements for the following xml

<ol>
<li>
    <a data- key="abc(/parent)" value="superval)">Parent</a> 
    <ol>
     <li>
        <a data-key="abc(/parent/1)" data-value="parent-val">Parent/1</a>
       <ol>
       <li>
          <a data-key="abc(/parent/1/1)" data-value="xyz">Parent/1/1</a>
       </li>
       <li>
          <a data-key="abc(/parent/1/2)" data-value="xyz">Parent/1/2</a>
       </li>
      <li>
          <a data-key="abc(/parent/1/3)" data-value="xyz">Parent/1/3</a>
       </li>
       <li>
          <a data-key="abc(/parent/1/4)" data-value="xyz">Parent/1/4</a>
       </li>
    </ol>
   </li>
 </ol>
 </li>
 <li>
  <a data-key="bcd/(parent1)" value="superval">Parent1</a>
 <ol>
     <li>
        <a data-key="bcd(/parent1/1)" data-value="parent-val">Parent1/1</a>
       <ol>
       <li>
          <a data-key="bcd(/parent1/1/1)" data-value="xyz">Parent1/1/1</a>
       </li>
       <li>
          <a data-key="bcd(/parent1/1/2)" data-value="xyz">Parent1/1/2</a>
       </li>
     <li>
          <a data-key="bcd(/parent1/1/3)" data-value="xyz">Parent1/1/3</a>
       </li>
       <li>
          <a data-key="bcd(/parent1/1/4)" data-value="xyz">Parent1/1/4</a>
       </li>
    </ol>
  </li>
 </ol>
</li>
</ol>

The above xml is just an example, and each parent can contain multiple child values. I need to search for elements with data-key values beginning from say ( parent/1/1/1 ) to ( parent/1/1/4 ), and for these keys extract the value of the attribute value associated with it. The data-key values can span different parents as well, like ( parent/1/1/1 ) to ( parent/1/1/2 ).

I need to create XPath expressions for two above scenarios. I've tried using this XPath expression

//*[@data-key='abc(/parent/1/1/1)'] 

but it only gives me a single <a> element, where as I need a range of elements. I'm totally new to XPath, so any help in this regard will be useful.

Many thanks in advance. Asheesh

Try using the contains() function, with the range you're looking for, like this:

//*[contains(@data-key,'abc(/parent/1/1/)')] 

This will give you all nodes with a data-key that has at least that root, such as in your example for (parent/1/1/1) to (parent/1/1/4). Although the xml snippet you provided doesn't contain data-keys of that range, you can edit the slashes/numbers to what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM