Filtrowanie Python Elementtree według XPath

Sep 04 2020

wyobraź sobie, że mam taki XML:

<root>
  <elements>
    <element> foo </element>
    <element is="false"> foo </element>
    <element is="false"> bli </element>
    <element is="false"> bla </element>
  </elements>
</root>

Jak mogę to zrobić:

import xml.etree.ElementTree as ET

root = ET.fromstring(XmlFromAbove)
res_a  = root.findall("element[@is='false']")) ##<- This gives me all elements with the specific attribute
res_b  = root.findall("element[not@is='false']")) ##<- This would be nice to give me all elements without that specific attribute (`<element> foo </element>` in this case)

Wiem, że res_bto nie zadziała, ale wydaje mi się, że jest to powszechny problem, więc ktoś ma pojęcie, jakie jest obejście tego problemu?

Aby zwrócić uwagę na to trochę bardziej (skopiowane z komentarzy)

Mogłem na pewno znaleźć element zawierający „foo”, ale chcę wiedzieć, czy istnieje sposób na znalezienie elementu, który NIE zawiera atrybutu = „false”.

Odpowiedzi

2 balderman Sep 04 2020 at 17:10

patrz poniżej

import xml.etree.ElementTree as ET

xml = '''<root>
  <elements>
    <element> foo </element>
    <element is="false"> foo </element>
    <element is="false"> bli </element>
    <element is="false"> bla </element>
    <element please="false"> no_is </element>
    <element is="true"> with_true_is </element>
  </elements>
</root>'''

root = ET.fromstring(xml)

no_is_lst = [e for e in root.findall('.//element') if 'is' not in e.attrib]
for e in no_is_lst:
    print(e.text)

wynik

 foo 
 no_is 
deadshot Sep 04 2020 at 16:59

Możesz użyć lxml

from lxml import etree

root = etree.fromstring(data)
res = root.xpath(".//element[not(@is)]")

print(res[0].text) #foo