如何检查每个< book>元素在XML文件中具有特定的子儿童
我想验证我的 XML 文件以检查每个
元素是否都有
的子子元素,如果缺少任何元素,则抛出错误。
我的 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):
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.
My XML looks like this:
<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
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):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ElementTree 的 XPath 支持非常有限,因此我认为您无法通过一次
findall
调用来完成此操作。如果您可以切换到 lxml,您可以使用 xpath() 并在一次调用中完成它...
这将返回:
带有当前输入。如果您删除
目标
(或重命名它),它将返回:ElementTree's XPath support is very limited, so I don't think you can do it with a single
findall
call.If you can switch to lxml, you could use
xpath()
and do it in a single call...This will return:
with the current input. If you remove a
target
(or rename it), it will return: