1
votes

I can add the XML node using the ElementTree, but this returns the output in one single line instead of a tree structure look alike when I open the xml file in text format. I also tried using the minidom.toprettyxml but I do not know how to add the output to original XML. Since I would like the script to be reproducible in other environments, I prefer not using external libraries such as lxml. Can someone please help how I can pretty print the output? - python 2.7

The Sample XML. This is how it looks both in text format and Explorer.

<?xml version="1.0" encoding="utf-8"?>
<default_locators >
  <locator_ref>
    <name>cherry</name>
    <display_name>cherrycherry</display_name>
    <workspace_properties>
      <factory_progid>Workspace</factory_progid>
      <path>InstallDir</path>
    </workspace_properties>
  </locator_ref>
</default_locators>

Expected Output in both text format and Explorer.

<?xml version="1.0" encoding="utf-8"?>
<default_locators >
  <locator_ref>
    <name>cherry</name>
    <display_name>cherrycherry</display_name>
    <workspace_properties>
      <factory_progid>Workspace</factory_progid>
      <path>InstallDir</path>
    </workspace_properties>
  </locator_ref>
  <locator_ref>
    <name>berry</name>
    <display_name>berryberry</display_name>
    <workspace_properties>
      <factory_progid>Workspace</factory_progid>
      <path>C:\temp\temp</path>
    </workspace_properties>
  </locator_ref>
</default_locators>

My script

#coding: cp932

import xml.etree.ElementTree as ET

tree = ET.parse(r"C:\DefaultLocators.xml")
root = tree.getroot()

locator_ref = ET.SubElement(root, "locator_ref")
name = ET.SubElement(locator_ref, "name")
name.text = " berry"
display_name = ET.SubElement(locator_ref, "display_name")
display_name.text = "berryberry"
workspace_properties = ET.SubElement(locator_ref, "workspace_properties")
factory_progid = ET.SubElement(workspace_properties,"factory_progid")
factory_progid.text = "Workspace"
path = ET.SubElement(workspace_properties, "path")
path.text = r"c:\temp\temp"

tree.write(r"C:\DefaultLocators.xml", encoding='utf-8')

Returned output. After running my script, new nodes are added to my sample.xml file, but it returns output in one single line, with all newlines and indents removed from the original sample.xml file. At least thats how it looks when I open the sample.xml file in text format. However, When I open the sample.xml file in Explorer, it looks fine. I still see the newlines and indents as they were before. How can I keep the original tree structure in text format even after running the script?

<default_locators>
  <locator_ref>
    <name>cherry</name>
    <display_name>cherrycherry</display_name>
    <workspace_properties>
      <factory_progid>Workspace</factory_progid>
      <path>InstallDir</path>
    </workspace_properties>
  </locator_ref>
<locator_ref><name> berry</name><display_name>berryberry</display_name><workspace_properties><factory_progid>Workspace</factory_progid><path>c:\temp\temp</path></workspace_properties></locator_ref></default_locators>
3

3 Answers

2
votes

when dealing with element, you can do like this: element.tail = '\n' then,it will be written in single line.

0
votes

write your xml in elementTree as:

import xml.etree.ElementTree as ET


def serialize_xml(write, elem, encoding, qnames, namespaces):
    tag = elem.tag
    text = elem.text
    if tag is ET.Comment:
        write("<!--%s-->" % _encode(text, encoding))
    elif tag is ET.ProcessingInstruction:
        write("<?%s?>" % _encode(text, encoding))
    else:
        tag = qnames[tag]
        if tag is None:
            if text:
                write(_escape_cdata(text, encoding))
            for e in elem:
                serialize_xml(write, e, encoding, qnames, None)
        else:
            write("\n<" + tag) ## '\n' added by namit
            items = elem.items()
            if items or namespaces:
                if namespaces:
                    for v, k in sorted(namespaces.items(),
                                       key=lambda x: x[1]):  # sort on prefix
                        if k:
                            k = ":" + k
                        write(" xmlns%s=\"%s\"" % (
                            k.encode(encoding),
                            _escape_attrib(v, encoding)
                            ))
                for k, v in sorted(items):  # lexical order
                    if isinstance(k, QName):
                        k = k.text
                    if isinstance(v, QName):
                        v = qnames[v.text]
                    else:
                        v = _escape_attrib(v, encoding)
                    write(" %s=\"%s\"" % (qnames[k], v))
            if text or len(elem):
                write(">")
                if text:
                    write(ET._escape_cdata(text, encoding))
                for e in elem:
                    serialize_xml(write, e, encoding, qnames, None)
                write("</" + tag + ">")
            else:
                write(" />")
    if elem.tail:
        write(ET._escape_cdata(elem.tail, encoding))

ET._serialize_xml=serialize_xml

tree = ET.parse(r"samplexml.xml")
root = tree.getroot()

locator_ref = ET.SubElement(root, "locator_ref")
name = ET.SubElement(locator_ref, "name")
name.text = " berry"
display_name = ET.SubElement(locator_ref, "display_name")
display_name.text = "berryberry"
workspace_properties = ET.SubElement(locator_ref, "workspace_properties")
factory_progid = ET.SubElement(workspace_properties,"factory_progid")
factory_progid.text = "WorkspaceFactory"
path = ET.SubElement(workspace_properties, "path")

ins_out=open("samplexml_1.xml",'wb',1000)
ET.ElementTree(locator_ref).write(ins_out,encoding="ASCII")
ins_out.close()

this will write complete file in single line; without adding white space in xml tail.

0
votes

I think you must try lxml library. It's the best way to parse XML in Python. It has magic argument *pretty_print* for such things. Here's an example:

import lxml.etree as etree

root = etree.Element("root")
for rn in range(10):
    etree.SubElement(root, "column_%s" % str(rn)).text = str(rn*rn)
pretty_data = etree.tostring(root, pretty_print=True, encoding = 'utf-8')
print final_data

Result:http://pastebin.com/y0rkQ78G