是的,您可以使用regular expressions in lxml xpath。
这是一个例子:
results = root.xpath(
"//*[re:test(local-name(), '^TEXT.*')]",
namespaces={'re': "http://exslt.org/regular-expressions"})
当然,在您提到的示例中,您实际上并不需要正则表达式。你可以使用starts-with() xpath 函数:
results = root.xpath("//*[starts-with(local-name(), 'TEXT')]")
完整的程序:
from lxml import etree
root = etree.XML('''
<root>
<TEXT1>one</TEXT1>
<TEXT2>two</TEXT2>
<TEXT3>three</TEXT3>
<x-TEXT4>but never four</x-TEXT4>
</root>''')
result1 = root.xpath(
"//*[re:test(local-name(), '^TEXT.*')]",
namespaces={'re': "http://exslt.org/regular-expressions"})
result2 = root.xpath("//*[starts-with(local-name(), 'TEXT')]")
assert(result1 == result2)
for result in result1:
print result.text, result.tag
解决一个新的需求,考虑这个 XML:
<root>
<tag>
<TEXT1>one</TEXT1>
<TEXT2>two</TEXT2>
<TEXT3>three</TEXT3>
</tag>
<other_tag>
<TEXT1>do not want to found one</TEXT1>
<TEXT2>do not want to found two</TEXT2>
<TEXT3>do not want to found three</TEXT3>
</other_tag>
</root>
如果想要查找所有TEXT 元素的直接子元素,它们是<tag> 元素:
result = root.xpath("//tag/*[starts-with(local-name(), 'TEXT')]")
assert(' '.join(e.text for e in result) == 'one two three')
或者,如果想要所有 TEXT 元素,它们只是第一个 tag 元素的直接子元素:
result = root.xpath("//tag[1]/*[starts-with(local-name(), 'TEXT')]")
assert(' '.join(e.text for e in result) == 'one two three')
或者,如果只想找到每个 tag 元素的第一个 TEXT 元素:
result = root.xpath("//tag/*[starts-with(local-name(), 'TEXT')][1]")
assert(' '.join(e.text for e in result) == 'one')
资源: