python xml.etree.ElementTree追加到子元素 [英] python xml.etree.ElementTree append to subelement

查看:657
本文介绍了python xml.etree.ElementTree追加到子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用xml.etree.ElementTree解析xml文件,查找特定标签,将一个子项附加到该标签,将另一个子项附加到新创建的标签并将文本添加到该子项。

I am trying to use xml.etree.ElementTree to parse a xml file, find a specific tag, append a child to that tag, append another child to the newly created tag and add text to the latter child.

我的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'的子项

This seems to work except 'c' appends as a child of 'a' rather then 'b'

就像这样:

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

此外,如何将文本添加到新创建的元素 c中?我可以迭代直到找到没有文本但必须有更好方法的标记'c'。

Also, how do I add text to the newly created element 'c'? I could iterate through until I find the a tag 'c' that has no text but there must be a better way.

推荐答案

您需要指定 b 作为 c 的父元素。

You need to specify b as a parent element for c.

此外,要获取 a 标记,您不需要循环-只需取根( a )。

Also, for getting the a tag you don't need a loop - just take the root (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>

这篇关于python xml.etree.ElementTree追加到子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆