Parse xml file using Python

from xml.dom import minidom

data = minidom.parse(“/path/to/xmlfile”)

#I need to get the “error” tags
errorlist = data.getElementsByTagName(“error”) 
error_types = []

for error in errorlist:
  if error.attributes[‘id’].value not in error_types:
    error_types.append(str(error.attributes[‘id’].value))

print error_types

 

A much better one is using the ElementTree,

 

import xml.etree.ElementTree as ET

data = ET.parse(/path/to/xmlfile)

root = data.getroot() #here root is “errors”

for error in root.findall(‘error’):

    print error.get(‘id’), error.find(‘location’).get(‘file’)

 

Example of my xml content:

“””

<errors>
<error id=”variableScope” severity=”style” msg=”The scope of the variable &apos;ch&apos; can be reduced.” verbose=”The scope of the variable &apos;ch&apos; can be reduced. Warning: Be careful when fixing this message, especially when there are inner loops. Here is an example where cppcheck will write that the scope for &apos;i&apos; can be reduced:
void f(int x)
{
int i = 0;
if (x) {
// it&apos;s safe to move &apos;int i = 0;&apos; here
for (int n = 0; n &lt; 10; ++n) {
// it is possible but not safe to move &apos;int i = 0;&apos; here
do_something(&amp;i);
}
}
}
When you see this message it is always safe to reduce the variable scope 1 level.”>
<location file=”build/fplt-a/flashwrite/src/bin2txt.c” line=”7″/>
</error>
<error id=”variableScope” severity=”style” msg=”The scope of the variable &apos;data&apos; can be reduced.” verbose=”The scope of the variable &apos;data&apos; can be reduced. Warning: Be careful when fixing this message, especially when there are inner loops. Here is an example where cppcheck will write that the scope for &apos;i&apos; can be reduced:
void f(int x)
{
int i = 0;
if (x) {
// it&apos;s safe to move &apos;int i = 0;&apos; here
for (int n = 0; n &lt; 10; ++n) {
// it is possible but not safe to move &apos;int i = 0;&apos; here
do_something(&amp;i);
}
}
}
When you see this message it is always safe to reduce the variable scope 1 level.”>
<location file=”build/fplt-a/flashwrite/src/bin2txt.c” line=”153″/>
</error>

</errors>

“””

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s