简体   繁体   English

python xml.etree.ElementTree附加到子元素

[英]python xml.etree.ElementTree append to subelement

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.etree.ElementTree来解析xml文件,查找特定标记,将子项附加到该标记,将另一个子项附加到新创建的标记并将文本添加到后一个子项。

My XML: 我的XML:

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

Desired XML: 期望的XML:

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

Current code: 当前代码:

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

This seems to work except 'c' appends as a child of 'a' rather then 'b' 这似乎有效,除了'c'作为'a'而不是'b'的孩子。

Like so: 像这样:

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

Also, how do I add text to the newly created element 'c'? 另外,如何将文本添加到新创建的元素“c”中? I could iterate through until I find the a tag 'c' that has no text but there must be a better way. 我可以迭代直到找到没有文字的标签'c',但必须有更好的方法。

You need to specify b as a parent element for c . 您需要将b指定为c的父元素。

Also, for getting the a tag you don't need a loop - just take the root ( a ). 另外,为了获得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)

prints: 打印:

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

I prefer to define my own function for adding text: 我更喜欢定义自己添加文本的功能:

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

Which then is very convenient to use as: 这样使用起来非常方便:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM