Accessing Element Attributes


from xml.dom import minidom xmldoc = minidom.parse('emails.xml') cNodes = xmldoc.childNodes print "\nTo Addresses\n===================" nList = cNodes[1].getElementsByTagName("to") for node in nList:     eList = node.getElementsByTagName("addr")     for e in eList:         if e.hasAttribute("type"):             if e.getAttribute("type") == "TO":                 print e.toxml()

The first step to accessing element attributes in a XML file is to parse the XML document using the minidom.parse(file) function to create a DOM tree object. The child nodes of the DOM tree can be accessed directly using the childNodes attribute, which is a list of the child nodes at the root of the tree.

Use the childNodes attribute to navigate the DOM tree, or search for the elements by their tag name, as described in the previous task, to find the nodes you are looking for.

Once you have found the node, determine whether the node does have the attribute by calling the hasAttribute(name) function of the node object, which returns true if the node does contain the attribute specified by name. If the node does have the attribute, then you can use the getAttribute(name) function to retrieve a string representation of the attribute value.

from xml.dom import minidom #Parse XML file to DOM tree xmldoc = minidom.parse('emails.xml') #Get nodes at root of tree cNodes = xmldoc.childNodes #Find attributes by name print "\nTo Addresses\n===================" nList = cNodes[1].getElementsByTagName("to") for node in nList:     eList = node.getElementsByTagName("addr")     for e in eList:         if e.hasAttribute("type"):             if e.getAttribute("type") == "TO":                 print e.toxml() print "\nCC Addresses\n===================" nList = cNodes[1].getElementsByTagName("to") for node in nList:     eList = node.getElementsByTagName("addr")     for e in eList:         if e.hasAttribute("type"):             if e.getAttribute("type") == "CC":                 print e.toxml() print "\nBC Addresses\n===================" nList = cNodes[1].getElementsByTagName("to") for node in nList:     eList = node.getElementsByTagName("addr")     for e in eList:         if e.hasAttribute("type"):             if e.getAttribute("type") == "BC":                 print e.toxml()


xml_attribute.py

To Addresses =================== <addr type="TO">bwdayley@novell.com</addr> <addr type="TO">bwdayley@novell.com</addr> CC Addresses =================== <addr type="CC">bwdayley@sfcn.org</addr> BC Addresses =================== <addr type="BC">bwdayley@sfcn.org</addr>


Output from xml_attribute.py code.



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net