How to define the XPath for either the span or in case the span isn't available take the div

Viewed 41

I've got a list of Products with prices and I'm looking for a way to create an XPath, where I want all prices extracted but in case there isn't a price instead there is just a product with a replacement message, I want to have the replacement message. This is an example of my script from two products, one with price and the other with replacement message:

        <div class="productInformations">
         <dl class="productPrice">
          <dt class="yourPrice">...</dt>
          <dd class="yourPrice">5,23$</dd>
         </dl>
        </div>
         ...
        <div class="productInformations">
          <div class="replacementPZNMessage">Not available at the moment</div>
        </div>

The closest XPath I've tried:

//dl[@class="productPrice"]//dd[@class="yourPrice"] | //div[@class="replacementPZNMessage"]

What is kinda working but I need the right order of the product prices and the not available ones. This XPath is extracting all of it but in the wrong order ( First all the prices, second all not available ones)! I need to extract the price so that product 1 is the first in my list and the same with product 2, what should be shown its existing as second product but not available. Please help me!

Have a nice day everyone

1 Answers

The result ordering could be something related to your implementation.
Also, dd is a child element of dl so no need for relative path separator.
Testing on Linux command line returns elements in document order as expected.

echo 'cat //dl[@class="productPrice"]/dd[@class="yourPrice"] | //div[@class="replacementPZNMessage"]' | xmllint --html --shell tmp.html 
/ > cat //dl[@class="productPrice"]/dd[@class="yourPrice"] | //div[@class="replacementPZNMessage"]
 -------
<dd class="yourPrice">5,23$</dd>
 -------
<div class="replacementPZNMessage">Not available at the moment</div>
 -------
<dd class="yourPrice">9999$</dd>
 -------
<div class="replacementPZNMessage">Not available at the moment</div>

Note: XPath 1.0 expressions should return the same result regardless of the language.

Related