英文:
How to copy an XML file and save it to the local device using python?
问题
我想复制一个带有标签的XML文件并对其进行修改,然后将此副本保存到本地桌面。
因此,我使用Python语言打开XML文件并使用ElementTree库。以下是Python代码:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
# 复制test.xml文件并将其保存到本地
mytree.write('test.xml')
有没有什么想法,我如何复制现有的XML文件并对其进行修改,然后保存到本地?
英文:
I want to copy a XML with its tags and modify it, and then save this copy to the local desktop.
So I use python language to open the XML file using ElementTree library.
And here is the code of python:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
#Copy the test.xml file and save it to the local
mytree.write('test.xml')
Is there any Idea how can I copy the existing XML file and modify it and then save it to the local?
答案1
得分: 0
我希望这对你的解决方案有用,
import xml.etree.ElementTree as ET
tree = ET.parse('./xml_stackoverflow.xml')
root = tree.getroot()
for compattrval in root.iter('CompAttrVal'):
compattrval_value = int(compattrval) + 1
# update the text of compattrval
compattrval.text = str(compattrval_value)
# update name attribute value or if it's not exist it will create a new attribute name
compattrval.set('name', 'updated_value')
tree.write('output.xml')
【注意】:我只翻译了代码部分,没有回答问题或提供额外内容。
英文:
I hope, it works for your solution,
import xml.etree.ElementTree as ET
tree = ET.parse('./xml_stackoverflow.xml')
root = tree.getroot()
for compattrval in root.iter('CompAttrVal'):
compattrval_value = int(compattrval) + 1
# update the text of compattrval
compattrval.text = str(compattrval_value)
# update name attribute value or if it's not exist it will create a new attribute name
compattrval.set('name', 'updated_value')
tree.write('output.xml')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论