Using the Python Modules
❘
283
A big difference between IronPython and
Python is how you write the XML to a file.
As previously mentioned, you can’t use the
xml.dom.ext.PrettyPrint()
method. In
this case, the code creates a file,
MyFile
,
using
open()
. The arguments define the
filename and the mode, where
‘w‘
signi-
fies write. In order to write the text to a
file, you use a two-step process. First, the
code creates formatting XML by calling
Doc.toprettyxml()
. The function accepts
an optional encoding argument, but there isn’t any way to define the resulting XML document as
stand-alone using the
standalone=“yes“
attribute (see Figure 13-1). Second, the code writes the
data to the file buffer using
MyFile.write()
.
Calling
MyFile.write()
doesn’t write the data to disk. In order to clear the
file buffer, you must call
MyFile.close()
. Theoretically, IronPython will call
MyFile.close()
when the application ends, but there isn’t any guarantee of
this behavior, so you must specifically call
MyFile.close()
to ensure there isn’t
any data loss.
The
DisplayDocument()
function comes next. Reading an XML document from disk and placing
it in a variable is almost too easy when using IronPython. All you need to do is make a single call to
xml.dom.minidom.parse()
. That’s it! The document is immediately ready for use.
The second step is to display the same output shown in Figure 13-2. Again, all you need in
IronPython is a simple
for
loop, rather than the somewhat lengthy .NET code. In this case,
you ask IronPython to retrieve the nodes you want using
XMLDoc.getElementsByTagName()
.
The output is a list that you can process one element at a time. The
print
statement calls on
a complex-looking call sequence.
ThisChild.firstChild.toxml().strip(‘\n\t’)
However, if you take this call sequence apart, it really isn’t all that hard to understand. Every iteration
of the loop places one of the
MsgNode
elements in
ThisChild
. The first (and only) child of
MsgNode
is
the
Message
text node, so you can retrieve it using the
firstChild
property. The
firstChild
property
contains a
DOM Text node
object, so you convert it to XML using the
toxml()
method. Unfortunately,
the resulting string contains control characters, so you remove them using the
strip(‘\n\t‘)
method.
The result is a simple value output.
Do'stlaringiz bilan baham: |