我想编辑XML文件中元素的属性。XML编辑属性
文件看起来像
<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
<Value>0.0</Value>
<Result>0.0</Result>
</Parameter>
我要替换的价值,结果从一个文本文件中的一些其他属性的值。
请建议。 在此先感谢。
我想编辑XML文件中元素的属性。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>
非常感谢您的建议。 其实在实际情况下,我有一个重复包含这些类元素的XML文件。 我想读取该XMl文件中的行并按照你所说的去做。 请给它一些提示。 感谢您的即时回复。 – manoj1123 2009-12-17 13:53:29
请修改您的问题(以上),而不是在评论中提出新问题。它更容易理解,另外,请始终在您的问题中包含代码/数据的相关部分,并提供一些关于您卡住的位置以及为什么(错误,例外,...)的提示 - 最后一点:更多人(rep-hunters)会回答此问题,如果它不是一个'社区维基' – miku 2009-12-17 14:04:14
并欢迎SO);) – miku 2009-12-17 14:09:19
是0.0 0.0是否有效?请发布更多的文件.. – miku 2009-12-17 12:58:05