将其他xml属性添加到子元素python

时间:2016-05-24 20:25:50

标签: python xml attributes elementtree

我正在尝试读取已处理的xml并使用elementtree向其添加第4个属性。

<ID_List>
 <Samples>
  <Sample>
    <Attribute Name="SampleID" Value="0000000"/>
    <Attribute Name="ListNumber" Value="0000000"/>
    <Attribute Name="TestID" Value="ABCDEFGHIJK"/>
 </Sample>
</ID_List>

我的代码到目前为止

import xml.etree.cElementTree as ET
tree = ET.ElementTree(file=<path>)
root = tree.getroot()
for subelem in root[2]: # IDlist is root[0], Samples is root[1] need to add attribute to root[3] sample
    for subelem2 in subelem:
        subelem2.set("Name", "4th attribute")

1 个答案:

答案 0 :(得分:0)

要添加新的属性标记,只需附加新标记:

from xml.etree import cElementTree as et

x = """<ID_List>
 <Samples>
  <Sample>
    <Attribute Name="SampleID" Value="0000000"/>
    <Attribute Name="ListNumber" Value="0000000"/>
    <Attribute Name="TestID" Value="ABCDEFGHIJK"/>
 </Sample>
 </Samples>
</ID_List>"""

xml = et.fromstring(x)

tag = xml.find(".//Samples/Sample")
new = et.Element("Attribute", dict(Name="Foo", Value="12345"))
tag.append(new)

print(et.tostring(xml))

哪会给你:

<ID_List>
 <Samples>
  <Sample>
    <Attribute Name="SampleID" Value="0000000" />
    <Attribute Name="ListNumber" Value="0000000" />
    <Attribute Name="TestID" Value="ABCDEFGHIJK" />
 <Attribute Name="Foo" Value="12345" />
</Sample>
 </Samples>
</ID_List>

更新文件:

In [4]: cat test.xml
<?xml version="1.0" encoding="utf-8"?>
<ID_List>
 <Samples>
  <Sample>
    <Attribute Name="SampleID" Value="0000000"/>
    <Attribute Name="ListNumber" Value="0000000"/>
    <Attribute Name="TestID" Value="ABCDEFGHIJK"/>
 </Sample>
 </Samples>
</ID_List>
In [5]: from xml.etree import cElementTree as et

In [6]: xml = et.parse("test.xml")

In [7]: tag = xml.find(".//Samples/Sample")

In [8]: tag.append(et.Element("Attrbute",{"Name":"Foo","Value":"12345"}))

In [9]: xml.write("test.xml")

In [10]: cat test.xml
<ID_List>
 <Samples>
  <Sample>
    <Attribute Name="SampleID" Value="0000000" />
    <Attribute Name="ListNumber" Value="0000000" />
    <Attribute Name="TestID" Value="ABCDEFGHIJK" />
 <Attrbute Name="Foo" Value="12345" /></Sample>
 </Samples>
</ID_List>