使用Python将标记添加到XML

时间:2019-03-20 20:18:49

标签: python xml web-deployment

 98 def add_field(xml):
 99     fields = """
100     <fields>
101         <field>
102             <column/>
103             <description/>
104             <datatype/>
105             <length/>
106         </field>
107         <field>
108             <column/>
109             <description/>
110             <datatype/>
111             <length/>
112         </field>
113     </fields>
114     """
115     #Insert new field into <fields>
116     root = ET.fromstring(fields)
117     new_field = ET.Element("field")
118     field_col = ET.SubElement(new_field, "column")
119     field_des = ET.SubElement(new_field, "description")
120     field_data = ET.SubElement(new_field, "datatype")
121     field_length = ET.SubElement(new_field, "length")
122     root.insert(0, new_field)

我正在尝试将新元素添加到现有XML文档中。默认情况下,有两个已编写,但是我想动态添加第三个。上面的代码没有给我任何错误,但是在我的XML文档上没有任何变化。

如何将新元素插入XML文档?

我要寻找的最终结果:

<fields>
    <field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
    <field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
   <field><column /><description /><datatype /><length /></field>
</fields>

1 个答案:

答案 0 :(得分:0)

root包含您的更改,您可以使用ElementTree的dump()调用来查看您的更改。因此,由于我们知道root包含您的更改,因此您必须通过转换为ElementTree并在其上调用write()来保存root:

import xml.etree.ElementTree as ET

fields = """
<fields>
    <field>
        <column/>
        <description/>
        <datatype/>
        <length/>
    </field>
    <field>
        <column/>
        <description/>
        <datatype/>
        <length/>
    </field>
</fields>
"""
#Insert new field into <fields>
root = ET.fromstring(fields)
new_field = ET.Element("field")
field_col = ET.SubElement(new_field, "column")
field_des = ET.SubElement(new_field, "description")
field_data = ET.SubElement(new_field, "datatype")
field_length = ET.SubElement(new_field, "length")
root.insert(0, new_field)

ET.dump(root)
tree = ET.ElementTree(root)
tree.write(open('test.xml','w'), encoding='unicode')

将打印出并产生具有相同内容的文件test.xml

<fields>
    <field><column /><description /><datatype /><length /></field><field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
    <field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
</fields>

已编辑以匹配已编辑的问题: 请停止编辑您的问题,使其与原始问题有所不同。

无论如何,insert()会将索引放置在要放置新元素的位置,因此,由于您希望新元素位于第三个位置(索引从0开始,因此是第二个索引),因此只需传递2而不是0:

root.insert(2, new_field)

哪个会产生:

<fields>
    <field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
    <field>
        <column />
        <description />
        <datatype />
        <length />
    </field>
<field><column /><description /><datatype /><length /></field></fields>
相关问题