Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML: How to get Elements by Attribute Value - Python 2.7 and minidom

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.

like image 808
Martin Avatar asked Jan 29 '14 10:01

Martin


People also ask

How do you read a specific tag in an XML file in Python?

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

What is XML Minidom?

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.

How do you traverse XML in Python?

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.


1 Answers

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.

like image 98
Xeun Avatar answered Nov 03 '22 01:11

Xeun