سؤال

I have an XML document which contains multiple tags with the same name, such as the following:

<record>
    <lang type="1">eng</lang>
    <lang>fra</lang>
</record>

Now, if I want to find Type 1 elements, I can use

root.findall("./lang[@type='1']")

But what if I want to find only the elements which do not have any attributes, like the second one? Obviously, I can find all elements and then do an if check or try, but is there a better way to do it?

هل كانت مفيدة؟

المحلول

ElementTree doesn't implement the full XPath language, so it's missing things like Booleans, Number and String comparison functions. As you've already realized, what you're looking to perform here is a negative attribute search, which isn't possible with the limited XPath implementation for ET.

The programmers for ET are relying on the comparator functionality of Python to provide those capabilities via the pythonic if, check, or try/except methodologies you've already mentioned.

نصائح أخرى

Iterate through your entire tree, printing all of the tags and attributes.

for el in tree.iter():
     print el.tag, el.attrib

Iterate through your tree starting at the record tag, printing all tags and attributes.

for el in tree.iter(tag='record'):
     print el.tag, el.attrib

Iterate through the lang tag(s).

for el in tree.iter(tag='lang'):
     print el.tag, el.attrib

I would also take a look at Processing XML in Python with ElementTree. That should help you in figuring out different ways to parse XML nodes.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top