Generating header information using ElementTree

John Machin sjmachin at lexicon.net
Sun Nov 26 19:07:50 EST 2006


Craig wrote:

> Great.  Got that sorted.  The problem I have now is that some of the
> XML data is not copied across to the file when I have the text
> information included.  The number of characters that is lost is equal
> to the number of characters that is in the block of text I entered
> before.  The code I am using is:
>
> def WriteXMLRecord ( record, XMLFileBaseName, root):
> RecordName = SubElement(root, "Log")
>     #iterate through all the fields in the record
>     for key in record:
>         # write the key and its data
>         test = SubElement(RecordName, key)
>         test.text = str(record[key])
>     tree = ElementTree(root)
>     tree.write(XMLFileBaseName)

I'm guessing, based on reading the docs for the write method, that you
should be using the file handle, rather than the file name, if the file
is already opened. So (1) change the name of the 2nd arg to
XMLFileHandle or somesuch, and in the caller, use outFile (the handle)
instead of "record.xml".

>
> def main():
>     outFile = open("record.xml", 'w')
>     outFile.write("""<?xml version=\"1.0\"?>
> <?xml-stylesheet type=\"text/xsl\" href=\"test.xsl\"?>
> <!DOCTYPE BobActivityLog SYSTEM \"test.dtd\">\n\n""")
>
>     root = Element("Log")
>     WriteXMLRecord(data1, "record.xml", root)
>     WriteXMLRecord(data2, "record.xml", root)
>     WriteXMLRecord(data3, "record.xml", root)
>     outFile.close()
> 
HTH,
John




More information about the Python-list mailing list