Extracting values from XML using Python

I have the following xml extracted from another xml file.

<notifications> <notification name="ccmSmtp" oid="" status="current"> <objects> <object module="callhome" name="ccmSmtp" /> </objects> <description>This is a description</description> </notification> <notification name="ccmAlertGroup" oid="" status="current"> <objects> <object module="callhome" name="callHome" /> </objects> <description>This is a description</description> </notification> <notification name="ccmAlert" oid="" status="current"> <objects> <object module="callhome" name="callHome" /> </objects> <description>This is a description</description> </notification> <notification name="ccmSmtp" oid="" status="current"> <objects></objects> <description>This is a description</description> </notification> </notifications>

I'm using the following Python code.

from xml.dom import minidom xmldoc = minidom.parse('example.xml') grammarNode = xmldoc.childNodes[2] notificationsNode = grammarNode.childNodes[9] print notificationsNode.toxml()

This python code gives the output of the xml which i have given above.

I tried the following to get the attribute values

notificationlist = xmldoc.getElementsByTagName('notification') print notificationlist[0].toxml() notification1 = notificationlist[0] key = notification1.attributes.keys()

Using this I'm able to get only the values of the fist set of notification.

How is that i can get all the values of the attributes and store it in separate variables?


If you want to get the attributes for each item in notificationlist, you could do this:

attrslist = [dict(node.attributes.items()) for node in notificationlist]
print attrslist[0]
# => {u'status': u'current', u'oid': u'', u'name': u'ccmSmtp'}
print attrslist[0]['status']
# => current

From here it would just be a matter of iterating this new list and pulling the attributes by name for each <notification> element in notificationlist.

for n in attrslist:
status = n['status']
oid = n['oid']
name = n['name']
# blah

Assuming that your 'notificationlist = xmldoc.getElementsByTagName('notification')' is generated from xmldoc which is the output value you listed you should have four elements. Thus just focusing on element 0 with notificationlist[0] will only address that first element. Here is some code with a modification to your samlpe xmldoc to make the discriptions differ by prepending aaa, bbb, ccc, ddd. You can capture the data by replacing the print statements---

for x in notificationlist:
print '*' * 15
print x.getElementsByTagName('description').item(0).childNodes[0].data
for y in x.attributes.keys():
print y
print x.attributes.getNamedItem(y).nodeValue
print '-' *15

aaaThis is a description

bbbThis is a description

cccThis is a description

dddThis is a description


Category:python Time:2011-04-20 Views:0

Related post

  • How to extract data from XML using python minidom 2011-09-08

    given this xml file, i would like to extract the data out from it. However, i have trouble extracting the data from <LandmarkPointListXml> onwards. The XML file: <?xml version="1.0" encoding="utf-8"?> <Map xmlns:xsi="http://www.w3.org/

  • Extracting text from XML using python 2011-10-07

    I have this example xml file <page> <title>Chapter 1</title> <content>Welcome to Chapter 1</content> </page> <page> <title>Chapter 2</title> <content>Welcome to Chapter 2</content>

  • Extract a specific XML message from a log file 2009-01-14

    i have a log file which contains hundreds/thousands of seperate XML messages and need to find a way to extract a complete xml message depending on the parameters given (values of nodes). My biggest problem is that even though i program a fair amount

  • Pretty printing XML in python 2009-04-15

    What is the best way (or even the various ways) to pretty print xml in python? --------------Solutions------------- import xml.dom.minidom xml = xml.dom.minidom.parse(xml_fname) # or xml.dom.minidom.parseString(xml_string) pretty_xml_as_string = xml.

  • Parsing XML in Python using ElementTree example 2009-11-23

    I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with: <timeSeriesRe

  • How do I parse XML in python? 2009-12-16

    I have many rows in a database that contain xml and I'm trying to write a python script that will go through those rows and count how many instances of a particular node attribute show up. For instance, my tree looks like: <foo> <bar>

  • How to send raw XML in Python? 2010-04-12

    I am trying to send raw xml to a service in Python. I have a the address of the service and my question is how would I wrap XML in python and send it to the service. The address is in the format below. 192.1100.2.2:54239 And say the XML is: <xml v

  • Write easily readable XML in Python 2010-04-22

    Is there any way other than creating a method myself to write XML using python which are easily readable? xMLFile.write(xmlDom.toxml()) does create proper xml but reading them is pretty difficult. I tried toprettyxml but doesn't seem like it does muc

  • xml to Python data structure using lxml 2010-04-30

    How can I convert xml to Python data structure using lxml? I have searched high and low but can't find anything. Input example <ApplicationPack> <name>Mozilla Firefox</name> <shortname>firefox</shortname> <description

  • C# Use Linq to Extract a single XML attribute for each XML file in a directory 2010-05-11

    How do I use Linq to extract a single XML attribute form each XML file in a directory and put that element in a C# list. Do I have to loop thru each file one-by-one? The XML files are quite large so I'd like to do this without loading the entire file

  • extract url from xml response 2010-08-17

    I need to extract url from XML response. Here is the XML response: <cloud xmlns:xlink="http://www.w3.org/1999/xlink"> <rootContainer xlink:href="https://api.example.net/v2/bucket/92FBC29C-344C-99CF-827E-1B5586A7F8E3" xlink:type="simple"/>

  • How to remove elements from XML using Python 2010-08-29

    I got stuck with XML and Python. The task is simple but I couldn't resolve it so far and spent on that long time. I came here for an advice how to solve it with couple of lines. Thanks for any help with traversing the tree. I always ended up with too

  • simple output of xml from python 2010-12-22

    I need to output XML from python in a very minimalist way: I can't use any external libraries beyond what's already in Python 2.6.5 I need to output XML tags, and text contents, with no attributes At this point I'm using print statements to explicitl

  • Extracting plaintext from XML with embedded links using XSLT 2011-11-03

    I am trying to extract text from XML similar to the following: <p>This is a paragraph <a href='http://link.com'>with an embedded link</a> with more text afterwards</p> I would like the extracted text to maintain the URL within

  • post form to remote URL and extract URL from XML reponse 2011-11-29

    Possible Duplicate: AJAX submit form to remote URL and extract URL from XML reponse What is the best way to prosess this form are there any form handeling scripts which can help I have a form which posts to remote url and returns a XML response conta

  • Extract data from xml 2012-01-04

    i came to know that the below sql can be used to extract data from xml SELECT A.B.value('(SearchField)[1]', 'VARCHAR(255)' ) SearchField, A.B.value('(FilterCondition)[1]', 'VARCHAR(25)' ) Operator, A.B.value('(ConditionData)[1]', 'VARCHAR(MAX)' ) Con

  • Commenting and uncommenting XML via Python 2012-01-06

    I would like to know of a way to comment and uncomment an element in XML using Python. <target depends="create-build-dir" name="build-Folio"> <property name="project.name" value="Folio"/> <ant antfile="build.xml" dir="Folio/FolioUI" in

  • Is there a formal method for 'walking' XML in Python? 2012-03-31

    I have been learning how to extract parts of XML using the dom.minidom function, and I can return specific elements and attributes successfully. I have a number of large XML files I want to parse, and push all the results into a db. Is there are a fu

  • Extract items list from XML in python 2011-05-10

    In python, what is the best way to extract the list of items from the following xml? <iq xmlns="jabber:client" to="[email protected]/8978528613056092673206" from="conference.localhost" id="disco" type="result"> <query xmlns="http:

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.446 (s). 13 q(s)