python xml.etree.ElementTree 附加到子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22772739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python xml.etree.ElementTree append to subelement
提问by andrsnn
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'? I could iterate through until I find the a tag 'c' that has no text but there must be a better way.
另外,如何向新创建的元素“c”添加文本?我可以迭代直到找到没有文本的标签“c”,但必须有更好的方法。
采纳答案by alecxe
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>
回答by Yonatan Simson
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')