Python xlxml xpath expression to match substring in attribute

Say I have below XML

<root> <element class="Page" style="background: url(/images/RlEguQY3_ghsdr.png?1324483033) repeat left top;" /> <element class="User" /> <element class="Image" src="/images/bg.png" /> </root> 

I am looking for an xpath expression that 1) matches all elements of / images in the style attribute and also 2) matches all elements of the image that have / images in the src attribute

Any help is much appreciated

thanks

+4
source share
3 answers
  //element[contains(@style, '/images') or (@class='Image' and contains(@src, '/images'))] 

(or something similar) should do it.

+7
source

I am looking for an xpath expression that 1) matches all elements that have /images in the style attribute

Directly translated into XPath :

 /*/element[contains(@style, '/images')] 

.,.

...

and 2) matches all Image elements that have /images in src attribute

The XML document provided does not have Image elements. You probably meant: element elements with a class attribute with the value "Image" :

 /*/element[@class='Image'][contains(@src, '/images')] 

Combined with each other, the above XPath expressions give :

 /*/element [contains(@style, '/images') or @class='Image' and contains(@src, '/images') ] 

It seems to me that the most likely for the second requirement above you really want the src attribute value to actually start with "/images" . If so, a more accurate XPath expression:

 /*/element [contains(@style, '/images') or @class='Image' and starts-with(@src, '/images') ] 
+1
source

You need to use predicates , your predicate expressions will use contains . The join operator may also come in handy.

0
source

Source: https://habr.com/ru/post/1387417/


All Articles