简体   繁体   中英

how to insert tabs instead of spaces when creating xml files in python

I m using

Creating a simple XML file using python

and

inserting newlines in xml file generated via xml.etree.ElementTree in python

but my xml subelement has 2 spaces from left, instead of a tab, how do I switch to a tab for a subelement and not 2 spaces?

Set indent argument of toprettyxml() to \\t :

from xml.dom import minidom
import xml.etree.cElementTree as ET

root = ET.Element("root")

doc = ET.SubElement(root, "doc")

field1 = ET.SubElement(doc, "field1")
field1.set("name", "blah")
field1.text = "some value1"

field2 = ET.SubElement(doc, "field2")
field2.set("name", "asdfasd")
field2.text = "some vlaue2"

dom = minidom.parseString(ET.tostring(root))
print dom.toprettyxml(indent='\t')

prints:

<?xml version="1.0" ?>
<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some vlaue2</field2>
    </doc>
</root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM