LISTINg 13-3:
Managing XML documents using the Python approach
# Import the required XML support.
import xml.dom.minidom
def CreateDocument():
# Create an XML document.
Doc = xml.dom.minidom.Document()
# Create the root node.
Root = Doc.createElement(‘root’)
# Add the message nodes.
MsgNode = Doc.createElement(‘Message’)
Message = Doc.createTextNode(‘Hello’)
MsgNode.appendChild(Message)
continues
548592c13.indd 281
2/24/10 12:48:59 PM
www.finebook.ir
282
❘
CHAPTER 13
Working With XML Data
Root.appendChild(MsgNode)
MsgNode = Doc.createElement(‘Message’)
Message = Doc.createTextNode(‘Goodbye’)
MsgNode.appendChild(Message)
Root.appendChild(MsgNode)
# Append the root node to the document.
Doc.appendChild(Root)
# Create the output document.
MyFile = open(‘Test2.XML’, ‘w’)
# Write the output.
MyFile.write(Doc.toprettyxml(encoding=’utf-8’))
# Close the document.
MyFile.close()
def DisplayDocument():
# Read the existing XML document.
XMLDoc = xml.dom.minidom.parse(‘Test2.XML’)
# Print the message node content.
for ThisChild in XMLDoc.getElementsByTagName(‘Message’):
print ‘Message:’, ThisChild.firstChild.toxml().strip(‘\n\t’)
CreateDocument()
DisplayDocument()
# Pause after the debug session.
raw_input(‘\nPress any key to continue...’)
The first thing you should notice is that the code for this example is much shorter than its .NET
counterpart, even though the result is essentially the same. Despite the problems with the Python
libraries, you can write concise code for manipulating XML using Python.
The code begins by importing the only module it needs,
xml.dom.minidom
. It then calls
CreateDocument()
and
DisplayDocument()
in turn, just as the .NET example does. In fact, the
output from this example is precisely the same. You see the same output shown in Figure 13-2
when you run this example.
The
CreateDocument()
function begins by creating an XML document,
Doc
, using
xml.dom
.minidom.Document()
. The XML document automatically contains the XML declaration, so
unlike the .NET version of the code, you don’t need to add it manually. So the first processing task
is to create the
root
node using
Doc.createElement(‘root‘)
.
As with the .NET example, this example creates two
MsgNode
elements that contain different messages.
The technique used is different from the .NET example. Instead of setting an
InnerXml
property, the
code creates an actual text node using
Doc.createTextNode()
. However, the result is the same, as
shown in Figure 13-6. The last step is to add
Root
to
Doc
using
Doc.appendChild()
.
LISTINg 13-3
(continued)
548592c13.indd 282
2/24/10 12:48:59 PM
www.finebook.ir
Do'stlaringiz bilan baham: |