如何使用Python复制一个XML文件并将其保存到本地设备?

huangapple go评论62阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年2月16日 15:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定