簡體   English   中英

Python,ElementTree:在 XML 標記中查找特定內容?

[英]Python, ElementTree: Find specific content in XML tag?

我正在嘗試做一些我認為在 ElementTree 中應該非常簡單的事情:查找具有特定標簽內容的元素。 文檔給出了示例:

*[tag='text']* Selects all elements that have a child named *tag* whose complete text content, including descendants, equals the given *text*.

這似乎很簡單。 但是,它不像我預期的那樣工作。 假設我想找到<note>NEW</note>的所有示例。 以下完整示例:

#!/usr/bin/env python
import xml.etree.ElementTree as ET

xml = """<?xml version="1.0"?>
<entry>
<foo>blah</foo>
<foo>bblic</foo>
<foo>fjdks<note>NEW</note></foo>
<foo>fdfsd</foo>
<foo>ljklj<note>NEW</note></foo>
</entry>
"""

root = ET.fromstring(xml)

print("Number of 'foo' elements: %d" % len(root.findall('.//foo')))
print("Number of new 'foo' elements: %d" % len(root.findall('.//[note="NEW"]')))

產量:

$ python foo.py 
Number of 'foo' elements: 5
Traceback (most recent call last):
  File "/usr/lib/python3.10/xml/etree/ElementPath.py", line 370, in iterfind
    selector = _cache[cache_key]
KeyError: ('.//[note="NEW"]',)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/foo.py", line 17, in <module>
    print("Number of new 'foo' elements: %d" % len(root.findall('.//[note="NEW"]')))
  File "/usr/lib/python3.10/xml/etree/ElementPath.py", line 411, in findall
    return list(iterfind(elem, path, namespaces))
  File "/usr/lib/python3.10/xml/etree/ElementPath.py", line 384, in iterfind
    selector.append(ops[token[0]](next, token))
  File "/usr/lib/python3.10/xml/etree/ElementPath.py", line 193, in prepare_descendant
    raise SyntaxError("invalid descendant")
SyntaxError: invalid descendant

我該怎么做這個簡單的任務?

docs還說

謂詞(方括號內的表達式)前面必須有標簽名稱、星號或其他謂詞。

考慮到這一點

root.findall('.//[note="NEW"]')

是非法的,你應該在[之前添加*來表示任何標簽,即

root.findall('.//*[note="NEW"]')

xor 在[之前使用標簽名稱來表示某些標簽,即

root.findall('.//foo[note="NEW"]')

主要問題似乎是從第一次搜索到第二次搜索的預期依賴關系,這種依賴關系不存在。

這有效(但使用的語法需要 Python >=3.10):

for foo in root.findall('.//foo[note="NEW"]'):
    print(foo.text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM