如何使用python更改xml文件的特定值
我有一个XML文件,其结构类似于:如何使用python更改xml文件的特定值,python,xml,elementtree,Python,Xml,Elementtree,我有一个XML文件,其结构类似于: <config> <property> <name>prop1</name> <value>1</value> </property> <property> <name>prop2</name> <value>2</value>
<config>
<property>
<name>prop1</name>
<value>1</value>
</property>
<property>
<name>prop2</name>
<value>2</value>
</property>
<property>
<name>prop3</name>
<value>3</value>
</property>
<property>
<name>prop4</name>
<value>4</value>
</property>
</config>
建议1
1.
建议2
2.
建议3
3.
建议4
4.
如何使用pythonxml.etree.ElementTree将prop3的值更改为10?您可以执行以下操作(只需查看lxml文档)
另外,您可以将最后一行更改为f.write(ET.tostring(root,encoding=“unicode”,pretty\u print=True))
以获得一个带有缩进和返回的漂亮XML文件。见下文。(不需要在所有元素上循环-使用“查找”方法并直接指向要修改的元素。也不需要使用外部库。)
有什么问题?你试过什么吗?
import lxml.etree as ET
file = "file.xml"
# Grab the root (config node)
root = ET.parse(file).getroot()
# Grab all 'property' nodes
properties = root.findall("property")
# Iterate over them
for property in properties:
# Find the property with name 'prop3'
if property.find("name").text == "prop3":
# Update the value to ten
property.find("value").text = "10"
# Write back the modified file
with open(file, "w") as f:
f.write(ET.tostring(root, encoding="unicode"))
import xml.etree.ElementTree as ET
xml = '''<config>
<property>
<name>prop1</name>
<value>1</value>
</property>
<property>
<name>prop2</name>
<value>2</value>
</property>
<property>
<name>prop3</name>
<value>3</value>
</property>
<property>
<name>prop4</name>
<value>4</value>
</property>
</config>'''
root = ET.fromstring(xml)
prop3 = root.find(".//property/[name='prop3']")
prop3_val = prop3.find('value')
print(prop3_val.text)
prop3_val.text = 10
print(prop3_val.text)
3
10