import xml.etree.ElementTree as ET
# 示例 XML 字符串
xml_data = '''<root>
<child name="child1">This is child 1</child>
<child name="child2">This is child 2</child>
</root>'''
# 解析 XML 字符串
root = ET.fromstring(xml_data)
# 遍历并打印所有子元素的标签和文本
for child in root:
print(f"Tag: {child.tag}, Text: {child.text}, Attributes: {child.attrib}")
# 创建一个新的 XML 元素
new_child = ET.Element('child', attrib={'name': 'child3'})
new_child.text = 'This is child 3'
# 将新元素添加到根元素中
root.append(new_child)
# 将修改后的 XML 转换为字符串并打印
print(ET.tostring(root, encoding='unicode'))
xml.etree.ElementTree
是 Python 标准库中的一个模块,用于解析和创建 XML 数据。xml_data
,包含一个根元素 <root>
和两个子元素 <child>
。ET.fromstring()
方法将 XML 字符串解析为一个 ElementTree 对象。for
循环遍历根元素的所有子元素,并打印每个子元素的标签、文本和属性。ET.Element()
创建一个新的 XML 元素,并设置其属性和文本内容。ET.tostring()
方法将修改后的 XML 转换为字符串并打印。希望这段代码能帮助你理解如何使用 Python 的 ElementTree
模块来解析和操作 XML 数据。
下一篇:resample函数python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站