Zoh*_*r81 4 python xml elementtree
我注意到python ElementTree模块在以下简单示例中更改了xml数据:
import xml.etree.ElementTree as ET
tree = ET.parse("./input.xml")
tree.write("./output.xml")
Run Code Online (Sandbox Code Playgroud)
我不会期望它会改变,因为我已经完成了简单的读写测试,没有进行任何修改。但是,结果显示了一个不同的故事,尤其是在名称空间索引中(普通–-ns0,d3p1-> ns1,i-> ns2):
<?xml version="1.0" encoding="utf-8"?>
<ServerData xmlns:i="http://www.a.org" xmlns="http://schemas.xxx/2004/07/Server.Facades.ImportExport">
<CreationDate>0001-01-01T00:00:00</CreationDate>
<Processes>
<Processes xmlns:d3p1="http://schemas.datacontract.org/2004/07/Management.Interfaces">
<d3p1:ProtectedProcess>
<d3p1:Description>/Applications/Safari.app/Contents/MacOS/Safari</d3p1:Description>
<d3p1:DiscoveredMachine i:nil="true" />
<d3p1:Id>0</d3p1:Id>
<d3p1:Name>/applications/safari.app/contents/macos/safari</d3p1:Name>
<d3p1:Path>/Applications/Safari.app/Contents/MacOS/Safari</d3p1:Path>
<d3p1:ProcessHashes xmlns:d5p1="http://schemas.datacontract.org/2004/07/Management.Interfaces.WildFire" />
<d3p1:Status>1</d3p1:Status>
<d3p1:Type>Protected</d3p1:Type>
</d3p1:ProtectedProcess>
</Processes>
</Processes>
Run Code Online (Sandbox Code Playgroud)
<ns0:ServerData xmlns:ns0="http://schemas.xxx/2004/07/Server.Facades.ImportExport" xmlns:ns1="http://schemas.datacontract.org/2004/07/Management.Interfaces" xmlns:ns2="http://www.a.org">
<ns0:CreationDate>0001-01-01T00:00:00</ns0:CreationDate>
<ns0:Processes>
<ns0:Processes>
<ns1:ProtectedProcess>
<ns1:Description>/Applications/Safari.app/Contents/MacOS/Safari</ns1:Description>
<ns1:DiscoveredMachine ns2:nil="true" />
<ns1:Id>0</ns1:Id>
<ns1:Name>/applications/safari.app/contents/macos/safari</ns1:Name>
<ns1:Path>/Applications/Safari.app/Contents/MacOS/Safari</ns1:Path>
<ns1:ProcessHashes />
<ns1:Status>1</ns1:Status>
<ns1:Type>Protected</ns1:Type>
</ns1:ProtectedProcess>
</ns0:Processes>
</ns0:Processes>
Run Code Online (Sandbox Code Playgroud)
ElementTree在使用ElementTree.register_namespace功能读取/写入xml之前,您需要使用来注册xml的名称空间及其前缀。范例-
import xml.etree.ElementTree as ET
ET.register_namespace('','http://schemas.xxx/2004/07/Server.Facades.ImportExport')
ET.register_namespace('i','http://www.a.org')
ET.register_namespace('d3p1','http://schemas.datacontract.org/2004/07/Management.Interfaces')
tree = ET.parse("./input.xml")
tree.write("./output.xml")
Run Code Online (Sandbox Code Playgroud)
如果没有此元素,则ElementTree将为相应的名称空间创建自己的前缀,这就是您的情况。
这在文档中给出-
xml.etree.ElementTree.register_namespace(prefix, uri)注册名称空间前缀。该注册表是全局注册表,并且将删除给定前缀或名称空间URI的所有现有映射。prefix是名称空间前缀。uri是一个名称空间uri。如果有可能,将使用给定的前缀序列化该命名空间中的标签和属性。
(强调我的)
| 归档时间: |
|
| 查看次数: |
1114 次 |
| 最近记录: |