gpt4 book ai didi

python - XML 编辑属性

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:45 24 4
gpt4 key购买 nike

我想编辑 XML 文件中元素的属性。

文件看起来像

<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
<Value>0.0</Value>
<Result>0.0</Result>
</Parameter>

我想用文本文件中的其他值替换值和结果属性。

请提出建议。提前致谢。

最佳答案

使用 ElementTree 的示例。它将用一些字符串替换 Value 元素文本; Result 元素的过程是类似的,此处省略:

#!/usr/bin/env python

xml = """
<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
<Value>0.0</Value>
<Result>0.0</Result>
</Parameter>
"""

from elementtree.ElementTree import fromstring, tostring

# read XML, here we read it from a String
doc = fromstring(xml)

for e in doc.findall('Value'):
e.text = 'insert your string from your textfile here!'

print tostring(doc)

# will result in:
#
# <Parameter mode="both" name="Spec 2 Circumference/Length" type="real">
# <Value>insert your string from your textfile here!</Value>
# <Result>0.0</Result>
# </Parameter>

关于python - XML 编辑属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1921601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com