我正在准备一个 Python 脚本来创建一个 XML,例如:
<?xml version="1.0" encoding="UTF-8"?>
<FileInfo>
<FileFormatVersion>1.0</FileFormatVersion>
<CustomerName>GCS0223</CustomerName>
<Source>nA</Source>
</FileInfo>
<Orders>
<Item>
<OrderCount>1</OrderCount>
我从论坛复制了一个脚本,它运行良好,但我还有一些额外的格式问题。这是我的工作代码
import xml.etree.cElementTree as ET
root = ET.Element("FileInfo")
#doc = ET.SubElement(root, "doc")
ET.SubElement(root, "FileFormatVersion").text = "1.0"
ET.SubElement(root, "CustomerName").text = "GCS0223"
ET.SubElement(root, "Source").text = "nA"
ET.SubElement(root, "OrderCount").text = "1"
tree = ET.ElementTree(root)
tree.write(r'c:\AH_Output\IGW.xml')
如何在“订单”和“商品”下缩进“订单计数”,如下所示:
<Orders>
<Item>
<OrderCount>1</OrderCount>
import xml.etree.ElementTree as ET
def create_xml():
# Create the root element
root = ET.Element("root")
# Create a child element
child1 = ET.SubElement(root, "child1")
child1.text = "This is child 1"
# Create another child element with an attribute
child2 = ET.SubElement(root, "child2")
child2.set("attribute", "value")
child2.text = "This is child 2"
# Create a sub-child element
subchild = ET.SubElement(child2, "subchild")
subchild.text = "This is a subchild of child 2"
# Convert the tree to a string
tree = ET.ElementTree(root)
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
if __name__ == "__main__":
create_xml()
print("XML file created successfully!")