python xml.etree.ElementTree 向子元素追加内容

10 投票
2 回答
43839 浏览
提问于 2025-04-18 00:44

我正在尝试使用 xml.etree.ElementTree 来解析一个 XML 文件,找到一个特定的标签,然后在这个标签下添加一个子标签,再在新创建的标签下添加另一个子标签,并给后者添加一些文本。

我的 XML 文件内容是:

<root>
<a>
    <b>
      <c>text1</c>
    </b>
    <b>
      <c>text2</c>
   </b>
</a>
</root>    

我想要的 XML 文件内容是:

<root>
<a>
    <b>
      <c>text1</c>
    </b>
    <b>
      <c>text2</c>
   </b>
    <b>
      <c>text3</c>
   </b>
</a>
</root>

我现在的代码是:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()


for x in root.iter():
    if (x.tag == 'a'):
        ET.SubElement(x, 'b')
        ET.SubElement(x, 'c')
        #add text

这个方法似乎有效,但 'c' 被添加为 'a' 的子标签,而不是 'b' 的子标签。

像这样:

<root>
<a>
    <b>
      <c>test1</c>
    </b>
    <b>
      <c>test2</c>
    </b>
  <b /><c/></a>
</root>

另外,我该如何给新创建的标签 'c' 添加文本呢?我可以通过循环查找没有文本的 'c' 标签,但肯定有更好的方法。

2 个回答

4

我更喜欢自己定义一个函数来添加文本:

def SubElementWithText(parent, tag, text):
    attrib = {}
    element = parent.makeelement(tag, attrib)
    parent.append(element)
    element.text = text
    return element

这样使用起来就非常方便了:

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

a = root.find('a')
b = ET.SubElement(a, 'b')
c = SubElementWithText(b, 'c', 'text3')
15

你需要把 b 设定为 c 的父元素。

另外,要获取 a 标签,你不需要用循环,只要直接取根元素(a)就可以了。

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

a = root.find('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(b, 'c')
c.text = 'text3'

print ET.tostring(root)

输出:

<root>
    <a>
        <b>
          <c>text1</c>
        </b>
        <b>
          <c>text2</c>
        </b>
        <b>
          <c>text3</c>
        </b>
    </a>
</root>

撰写回答