使用Python的Etree设置XML的属性值

时间:2015-07-11 20:19:59

标签: python xml elementtree

我正在尝试使用Python的Etree模块修改XML。我试图通过一个相当复杂的XML查找扫描项目'。 ScanItem的子项有三个键([' name',' type',' value'])。我希望修改' value'的内容。

到目前为止,这是我的代码:

from lxml import etree

model_dir = 'D:\MPhil\Model_Building\Models\Retinoic_acid\[07]\Model_LIne_10'
model_name = 'M28.cps'
model_file=os.path.join(model_dir,model_name) #model_file contains the XML

IA=Identifiability_Analysis() # custom class
copasiML_str= IA.read_copasiML_as_string(model_file)
copasiML=etree.fromstring(copasiML_str) # parse XML with etree
parameters_dict=IA.extract_parameters_to_dict(model_file) #extract some parameters from the XML
reaction_name_i='v1'
parameter_name_i='Kcat'
maxi = float(parameters_dict[reaction_name_i][parameter_name_i])*2 #calculating changes
mini = float(parameters_dict[reaction_name_i][parameter_name_i])/2 # calculating changes

query = "//*[@name='ScanItem']"  #looks for the element called ScanItem
for j in copasiML_i.xpath(query):
    children = list(j) #gets the children of ScanItem
    for k in children:
        if k.attrib['name']=='Maximum': #finds the 'bit' that I want to change
            copasiML_i.set(k.attrib['value'],maxi) #an attempt at changing the value to maxi. This does not work

最后一行给出以下错误:

ValueError: Invalid attribute name u'0.0102086'  #which is the value of 'maxi'

有人知道我做错了什么吗?

由于

1 个答案:

答案 0 :(得分:0)

所以我最终弄明白了。 它是一个简单的赋值,使用与普通Python字典相同的语法