Python在xml中添加子元素
在Python中,可以使用
xml.etree.ElementTree
模块来操作XML文档。要添加子元素,可以按照以下步骤进行操作:
- 导入
xml.etree.ElementTree
模块:
python复制代码
import xml.etree.ElementTree as ET
- 1
- 2
- 3
- 创建根元素:
python复制代码
root = ET.Element("root")
- 1
- 2
- 3
- 创建子元素并添加到根元素中:
python复制代码
child = ET.SubElement(root, "child")
- 1
- 2
- 3
child`变量中存储了新创建的子元素。第一个参数是父元素,第二个参数是子元素的标签名。
4. 为子元素添加属性:
python复制代码
child.attrib["name"] = "child1"
- 1
- 2
- 3
- 为子元素添加文本内容:
python复制代码
child.text = "This is a child element"
- 1
- 2
- 3
- 将XML文档写入文件:
tree = ET.ElementTree(root)
tree.write("example.xml")
- 1
- 2
完整代码如下所示:
import xml.etree.ElementTree as ET
root = ET.Element("root")
child = ET.SubElement(root, "child")
child.attrib["name"] = "child1"
child.text = "This is a child element"
tree = ET.ElementTree(root)
tree.write("example.xml")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
执行以上代码后,会在当前目录下生成名为example.xml
的XML文件,文件内容如下所示:
<root>
<child name="child1">This is a child elementchild>
root>
- 1
- 2
- 3
评论记录:
回复评论: