當前位置:成語大全網 - 新華字典 - 如何用Python構造壹個xml計數器

如何用Python構造壹個xml計數器

代碼

import xml.etree.cElementTree as ET

import xml.etree.ElementTree as ElementTree

from xml.dom.minidom import parseString

root = ET.Element("root")

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

ET.SubElement(doc, "field1", name="k1").text = "1<2"ET.SubElement(doc, "field2", name="k2").text = "2>1"tree = ET.ElementTree(root)

tree.write("filename.xml")

xml = ElementTree.tostring(root)

print(xml)

prettyxml = parseString(xml).toprettyxml()

print(prettyxml)123456789101112131415161718

輸出

b'<root><doc><field1 name="k1">1<2</field1><field2 name="k2">2>1</field2></doc></root>'<?xml version="1.0" ?><root>

<doc>

<field1 name="k1">1<2</field1>

<field2 name="k2">2>1</field2>

</doc></root>12345678

~ cat filename.xml

<root><doc><field1 name="k1">1<2</field1><field2 name="k2">2>1</field2></doc></root>%