[英]How to check if each <book> element has a specific subchild in xml file
I want to validate my XML file to check if every <book>
element has a sub-child of <target>
and throw error if any is missing.我想验证我的 XML 文件以检查每个
<book>
元素是否都有<target>
的子元素,如果有任何缺失则抛出错误。
My XML looks like this:我的 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>
Can someone advice me how to proceed this with etree.ElementTree有人可以建议我如何使用 etree.ElementTree 进行此操作
I tried with this, is it possible to do it in one call?我试过这个,是否可以在一个电话中完成?
count_books = len(tree.findall(".//books"))
count_target = len(tree.findall(".//target"))
if (count_books != count_target):
ElementTree's XPath support is very limited, so I don't think you can do it with a single findall
call. ElementTree 的 XPath 支持非常有限,所以我认为您无法通过单个
findall
调用来完成。
If you can switch to lxml, you could use xpath()
and do it in a single call...如果你可以切换到 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)}")
This will return:这将返回:
Are there any book elements without a target? - False
with the current input.与当前输入。 If you remove a
target
(or rename it), it will return:如果您删除
target
(或重命名它),它将返回:
Are there any book elements without a target? - True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.