gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:33 24 4
gpt4 key购买 nike

我想修改XML文件edmx:ReferenceUri的所有属性值。

我的文件(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 的属性值到同一个文件?

最佳答案

这里我们定义了寄存器命名空间,这段代码可以改变引用的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")

关于python - 动态修改 XML 文件中特定属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537354/

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