I want to get a list of XML Elements based first on TagName and second on Attribute Value. I´m using the xml.dom library and python 2.7.
While it´s easy to get the first step done:
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PFD = xmldoc.getElementsByTagName("PFD")
PNT = PFD.getElementsByTagName("PNT")
I´ve been looking around but cannot find a solution for the second step. Is there something like a .getElementsByAttributeValue
that would give me a list to work with?
If the XML looks like this
<PFD>
<PNT A="1" B=.../>
<PNT A="1" B=.../>
<PNT A="2" B=.../>
</PFD>
In need all PNTs where A="1" in a list.
To read an XML file, firstly, we import the ElementTree class found inside the XML library. Then, we will pass the filename of the XML file to the ElementTree. parse() method, to start parsing. Then, we will get the parent tag of the XML file using getroot() .
xml. dom. minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller. Users who are not already proficient with the DOM should consider using the xml.
There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.
If you don't find a built-in method, why not iterate over the items?
from xml.dom import minidom
xmldoc = minidom.parse(r"C:\File.xml")
PFD = xmldoc.getElementsByTagName("PFD")
PNT = xmldoc.getElementsByTagName("PNT")
for element in PNT:
if element.getAttribute('A') == "1":
print "element found"
Adding the items to a list should be easy now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With