动态修改XML文件中特定属性的值

时间:2018-03-28 14:34:41

标签: python xml xml-parsing elementtree

我想修改XML文件Uriedmx:Reference的所有属性值。

我的文件(Chassis.xml)内容为

<?xml version="1.0" encoding="UTF-8"?>

<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <edmx:Reference Uri="http://docs.oasis-open.org/odata/odata/v4.0/errata03/csd01/complete/vocabularies/Org.OData.Measures.V1.xml">
    <edmx:Include Namespace="Org.OData.Measures.V1" Alias="Measures"/>
  </edmx:Reference>
  <edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/RedfishExtensions_v1.xml">
    <edmx:Include Namespace="RedfishExtensions.v1_0_0" Alias="Redfish"/>
    <edmx:Include Namespace="Validation.v1_0_0" Alias="Validation"/>
  </edmx:Reference>
  <edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Resource_v1.xml">
    <edmx:Include Namespace="Resource"/>
    <edmx:Include Namespace="Resource.v1_0_0"/>
    <edmx:Include Namespace="Resource.v1_1_0"/>
  </edmx:Reference>
  <edmx:Reference Uri="http://redfish.dmtf.org/schemas/v1/Thermal_v1.xml">
    <edmx:Include Namespace="Thermal"/>
  </edmx:Reference>
</edmx:Edmx>

我能够读取Uri的所有值,但无法动态更新值到同一个文件。用于获取Uri值的代码是

import xml.etree.ElementTree as ET
tree = ET.parse('Chassis.xml')
root = tree.getroot()

for item in root.findall('{http://docs.oasis-open.org/odata/ns/edmx}Reference'):
    if 'Uri' in item.attrib:
        item.attrib['Uri']="new-uri"
ET.write("Chassis.xml")    

我的问题如何动态地读取和修改Uri的属性值到同一个文件?

1 个答案:

答案 0 :(得分:2)

这里我们定义寄存器名称空间,这段代码可以改变参考文献的Uri:

import xml.etree.ElementTree as ET
tree = ET.parse('Chassis_v1.xml')
root = tree.getroot()

for item in root.findall('{http://docs.oasis-open.org/odata/ns/edmx}Reference'):
    if 'Uri' in item.attrib:
    a=item.attrib['Uri']
        b=a.rsplit('/', 1)[1]
        item.attrib['Uri']="/redfish/v1/schemas/"+b

ET.register_namespace('edmx','http://docs.oasis-open.org/odata/ns/edmx')
ET.register_namespace('','http://docs.oasis-open.org/odata/ns/edm')
tree.write("Chassis_v1.xml",xml_declaration=True,encoding='utf-8',method="xml")