Loading an XML Document


from xml.dom import minidom DOMTree = minidom.parse('emails.xml') print xmldoc.toxml()

The easiest way to quickly load an XML document is to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that will quickly create a DOM tree from the XML file.

The sample phrase calls the parse(file [,parser]) function of the minidom object to parse the XML file designated by file into a DOM tree object. The optional parser argument allows you to specify a custom parser object to use when parsing the XML file.

Note

The DOM tree object can be converted back into XML by calling the toxml() function of the object, which returns a string containing the full contents of the XML file.


from xml.dom import minidom #Open XML document using minidom parser DOMTree = minidom.parse('emails.xml') #Print XML contents print DOMTree.toxml()


xml_open.py

<?xml version="1.0" ?><!DOCTYPE emails [         <!ELEMENT email (to, from, subject,  date, body)>         <!ELEMENT to (addr+)>         <!ELEMENT from (addr)>         <!ELEMENT subject (#PCDATA)>         <!ELEMENT date (#PCDATA)>         <!ELEMENT body (#PCDATA)>         <!ELEMENT addr (#PCDATA)>         <!ATTLIST addr type (FROM | TO |  CC | BC) "none">     ]><emails>     <email>         <to>             <addr type="TO">bwdayley@novell.com</addr>             <addr type="CC">bwdayley@sfcn.org</addr>         </to>         <from>             <addr type="FROM">ddayley@sfcn.org</addr>         </from>         <subject>         Update List         </subject>         <body>         Please add me to the list.         </body>     </email>     <email>         <to>             <addr type="TO">bwdayley@novell.com</addr>             <addr type="BC">bwdayley@sfcn.org</addr>         </to>         <from>             <addr type="FROM">cdayley@sfcn.org</addr>         </from>         <subject>         More Updated List         </subject>         <body>         Please add me to the list also.         </body>     </email> </emails>


Output from xml_open.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