Динамическое изменение значения определенных атрибутов в файле XML

Я хочу изменить все значения атрибутов Uri в edmx:Reference файла XML.

Содержимое моего файла (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 динамически в один и тот же файл?


person gvs    schedule 28.03.2018    source источник
comment
Вам нужно показать код Python, с которым вы работали.   -  person Tomalak    schedule 28.03.2018
comment
@Tomalak Обновил вопрос   -  person gvs    schedule 28.03.2018


Ответы (1)


Здесь мы определяем пространства имен регистров, и этот код может изменить 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")
person gvs    schedule 29.03.2018