XPath: Selecting elements having a child at a specified position of a specified type

StackOverflow https://stackoverflow.com/questions/23610317

  •  20-07-2023
  •  | 
  •  

سؤال

Looking at the following XML-Example:

<bookstore>
    <book>
        <title lang="eng">Harry Potter</title>
        <price>29.99</price>
    </book>
    <book>
        <price>39.95</price>
        <title lang="eng">Learning XML</title>
    </book>
</bookstore> 

Using XPath i wan't to select all books with first child being a title element and second child being a price element. This would return the first book in the example.

I tried the following expression:

book[title[1] and price[2]]

But this expression doesn't match, because it's selecting all books with at least one title element and with at least two price elements. How can i change this expression to select all books with first child being a title element and second child being a price element?

هل كانت مفيدة؟

المحلول

You can do it by getting the title child and check if there is the following price sibling:

//book[title/following-sibling::price]

Demo (using xmllint):

$ xmllint input.xml --xpath '//book[title/following-sibling::price]'
<book>
        <title lang="eng">Harry Potter</title>
        <price>29.99</price>
</book>

Another approach would be to check the name()s of the first and second children of book node:

//book[name(*[1]) = "title" and name(*[2]) = "price"]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top