如何在 python 中的给定 XML 标签下添加新条目
How to add a new entry under a given XML tag in python
我需要修改 python 中的一个 xml 文件;具体来说,我需要在 video
标签下添加一个新条目。例如,有这样的东西
<sources>
<programs>
<default pathversion="1"></default>
</programs>
<video>
<default pathversion="1"></default>
<source>
<name>Dir 1</name>
<path pathversion="1">/path/to/dir1/</path>
<allowsharing>true</allowsharing>
</source>
<source>
<name>Dir 2</name>
<path pathversion="1">/path/to/dir2/</path>
<allowsharing>true</allowsharing>
</source>
</video>
<music>
<default pathversion="1"></default>
</music>
<pictures>
<default pathversion="1"></default>
</pictures>
</sources>
我需要在 <video>...</video>
下创建一个新条目,如下所示:
<source>
<name>Dir 3</name>
<path pathversion="1">/path/to/dir3/</path>
<allowsharing>true</allowsharing>
</source>
并更新原始 xml 文件。这样做的最佳做法是什么?
使用xml.etree.ElementTree
插入。
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
insertLoc = root.findall("./video")[0]
start1 = ET.Element(insertLoc)
insSource = ET.SubElement(start1, "source")
insName = ET.SubElement(insSource, "name")
insName.text = "Dir 3"
insPath = ET.SubElement(insSource, "path")
insPath.attrib = {'pathversion':"1"}
insPath.text = "/path/to/dir3/"
insAllow = ET.SubElement(insSource, "allowsharing")
insAllow.text="true"
insertLoc.append(insSource)
print(ET.dump(tree))
我需要修改 python 中的一个 xml 文件;具体来说,我需要在 video
标签下添加一个新条目。例如,有这样的东西
<sources>
<programs>
<default pathversion="1"></default>
</programs>
<video>
<default pathversion="1"></default>
<source>
<name>Dir 1</name>
<path pathversion="1">/path/to/dir1/</path>
<allowsharing>true</allowsharing>
</source>
<source>
<name>Dir 2</name>
<path pathversion="1">/path/to/dir2/</path>
<allowsharing>true</allowsharing>
</source>
</video>
<music>
<default pathversion="1"></default>
</music>
<pictures>
<default pathversion="1"></default>
</pictures>
</sources>
我需要在 <video>...</video>
下创建一个新条目,如下所示:
<source>
<name>Dir 3</name>
<path pathversion="1">/path/to/dir3/</path>
<allowsharing>true</allowsharing>
</source>
并更新原始 xml 文件。这样做的最佳做法是什么?
使用xml.etree.ElementTree
插入。
import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
insertLoc = root.findall("./video")[0]
start1 = ET.Element(insertLoc)
insSource = ET.SubElement(start1, "source")
insName = ET.SubElement(insSource, "name")
insName.text = "Dir 3"
insPath = ET.SubElement(insSource, "path")
insPath.attrib = {'pathversion':"1"}
insPath.text = "/path/to/dir3/"
insAllow = ET.SubElement(insSource, "allowsharing")
insAllow.text="true"
insertLoc.append(insSource)
print(ET.dump(tree))