Home > other >  How to check if each <book> element has a specific subchild in xml file
How to check if each <book> element has a specific subchild in xml file

Time:03-31

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):

CodePudding user response:

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...

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:

Are there any book elements without a target? - True
  • Related