Generating header information using ElementTree

Craig craigtw.online at gmail.com
Sun Nov 26 18:17:58 EST 2006


Diez B. Roggisch wrote:

> Craig schrieb:
> > Fredrik Lundh wrote:
> >
> >> Craig wrote:
> >>
> >>> I'm only new to Python so please bear with me.  I using ElementTree to
> >>> generate an XML file that will reference a DTD and an XSL file.  The
> >>> header information I want at the start of the file is as follows:
> >>>
> >>> <?xml version="1.0"?>
> >>> <?xml-stylesheet type="text/xsl" href="test.xsl"?>
> >>> <!DOCTYPE BobActivityLog SYSTEM "test.dtd">
> >>>
> >>> How do you add this header information to the tree
> >> to the file, you mean?  use print.
> >>
> >> </F>
> >
> > Thanks for the quick response.  Here is the code I am using to manually
> > write to the file is:
> >
> >     outFile = open("record.xml", 'w')
> >     outFile.write = ("<?xml version=\"1.0\"?>\n")
> >     outFile.write = ("<?xml-stylesheet type=\"text/xsl\"
> > href=\"test.xsl\"?>\n")
> >     outFile.write = ("<!DOCTYPE BobActivityLog SYSTEM \"test.dtd\">\n")
> >     outFile.close()
> >
> > When I run the code I get the following error message:
> >
> > Traceback (most recent call last):
> >   File "bob-xml.py", line 189, in <module>
> >     main()
> >   File "bob-xml.py", line 173, in main
> >     outFile.write = ("<?xml version=\"1.0\"?>\n")
> > AttributeError: 'file' object attribute 'write' is read-only
> >
> > What am I doing wrong here?  If anyone could help that would be
> > appreciated.  Thanks again.
>
> write is a method, not a property.
>
> outFile.write("whatever")
>
> is the way to go...
>
> Diez

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)

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()

Any help would be appreciated.  Thanks and good luck.


Craig




More information about the Python-list mailing list