我想驗證我的 XML 檔案以檢查每個<book>元素是否都有一個子元素,<target>如果缺少任何元素則拋出錯誤。
我的 XML 如下所示:
<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0"><course id="cr1"><book id="bk1"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk2"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk3"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk4"><dek><source>ssf</source><target>ssf</target></dek></book>
</course>
<course id="cr2"><book id="bk1"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk2"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk3"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk4"><dek><source>ssf</source><target>ssf</target></dek></book>
</course>
</xliff>
有人可以建議我如何使用 etree.ElementTree 進行此操作
我試過這個,是否可以在一個電話中完成?
count_books = len(tree.findall(".//books"))
count_target = len(tree.findall(".//target"))
if (count_books != count_target):
uj5u.com熱心網友回復:
ElementTree 的 XPath 支持非常有限,所以我認為您不能通過一次findall呼叫來完成。
如果您可以切換到 lxml,您可以xpath()在一次呼叫中使用并完成它......
from lxml import etree
xml = """<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0"><course id="cr1"><book id="bk1"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk2"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk3"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk4"><dek><source>ssf</source><target>ssf</target></dek></book>
</course>
<course id="cr2"><book id="bk1"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk2"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk3"><dek><source>ssf</source><target>ssf</target></dek></book>
<book id="bk4"><dek><source>ssf</source><target>ssf</target></dek></book>
</course>
</xliff>
"""
tree = etree.fromstring(xml)
ns = {"x": "urn:oasis:names:tc:xliff:document:2.0"}
bad_books = tree.xpath('.//x:book[not(.//x:target)]', namespaces=ns)
print(f"Are there any book elements without a target? - {bool(bad_books)}")
這將回傳:
Are there any book elements without a target? - False
與當前輸入。如果您洗掉一個target(或重命名它),它將回傳:
Are there any book elements without a target? - True
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/452987.html
標籤:Python xml python-3.7 元素树
