开发者

Find attribute names that start with a certain pattern

开发者 https://www.devze.com 2023-01-24 17:32 出处:网络
I am looking to find all attributes of an element that match a certain pattern. So for an element <element s2=\"1\" name=\"aaaa\" id=\"1\" />

I am looking to find all attributes of an element that match a certain pattern.

So for an element

<element s2="1" name="aaaa" id="1" />
<element s3="1" na开发者_高级运维me="aaaa" id="2" />

I would like to be able to find all attributes that start with 's' (returning the value of s1 for the first element and s3 for the value of the second element).

If this is outside of xpath's ability please let me know.


Use:

element/@*[starts-with(name(), 's')]

This XPath expression selects all atribute nodes whose name starts with the string 's' and that are attributes of elements named element that are children of the current node.

starts-with() is a standard function in XPath 1.0


element/@*[substring(name(), 1,1) = "s"]

will match any attribute that starts with 's'.

The function starts-with() might look better than using substring()


I've tested the given answers from both @Dimitre-Novatchev and @Ledhund, using lxml.html module in Python.

Both element/@*[starts-with(name(), 's')] and element/@*[substring(name(), 1,1) = "s"] return only the values of s2 and s3. You won't be able to know which value belong to which attribute.

I think in practice I would be more interested in finding the elements themselves that contain the attributes of names starting with specific characters rather than just their values.

To achieve that is very simple, just add /.. at the end,

element/@*[starts-with(name(), "s")]/..

or

element/@*[starts-with(name(), "s")]/parent::*

or

element/@*[starts-with(name(), "s")]/parent::node()


None from above worked for me. So I did not some changes and it worked for me. :)

/*:UserCustomField[starts-with(@name, 'purchaseDate')]
0

精彩评论

暂无评论...
验证码 换一张
取 消