Python XML解析器使用名称空间前缀而不是默认名称空间xmlns

时间:2017-07-10 12:03:15

标签: python xml xml-parsing xml-namespaces

我使用std::terminate来解析XML,进行一些微调,并将修改后的内容写入另一个文件。

xml.etree

XML输入是:

import xml.etree.ElementTree as et
...
tree = et.parse(inputfile)
root = tree.getroot()
...
...
tree.write(outputfile)

输出结果为:

<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Header>
<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>SV/7kINewjtWHpy6XvepsVOfcDhx/EEkFkY9uZZEmvg8Fz90OOiuPXPIy7eX395TPnS1anCnNulHcWHVnSBqyb4CeEStJsf3KRD7KanCHJc3T2jaHuqyBumHY8Hut1L29z/daUIFC3SbeYmKmviBwITr2kN6WfqtnQ3XPjrLz9hiWS+4Yh+k7lt0EQX3Osal5bqmfA3V65FYY2IX7vxwI9ZIWW4a7Nfw8EWCEo6X8tN8uN4xs4aKQaisTD6BjRHjsFqLf0i0Tt2oGpqCPuXG/E8rFqrck0PSa6tLxTzxkt80/w0upjI03EzTErVeayIVSPAzmVn3fkoYnqtMGYgL7UHIkcgptb7YZo5e65cxh7vlrcVgRAl8++7FVN9drmQoKJnu2DYWE3LFmbZTyEjQXaVxR3kuQvwyZUjennidG5z/V4HkJtTou738nAZwloS6A3sqHpLRhoUGvtpifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA+T0XMCGfOLVPY6L2iYCeoj9de6DXSgvwHbO2KSmQPfdoJ05+B2oLkwDLAIz6yGMAmk00CwjBe2sJkr4Gz9TTDx9OBRdRjVC/uf0CX2KVwsKFE5apt2YeNq4WE1b8ZRy6NPyZvVdxXjf4FpA0O8G3bdr96xHNmHlHJI57J2kmnUU2IHsOEbk1OSlBsN8=</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>
</Header>

当然,这是一个完全有效的,虽然有些奇怪的XML,因为命名前缀ns0:XXX

我希望输出像上面的原始XML一样,使用xmlns = XXX绑定在被考虑的元素而不是顶级使用xmlns:ns0 = XXX。

我尝试使用<Envelope xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ns0="http://www.w3.org/2001/04/xmlenc#"> <Header> <Security> <Transport_key> <ns0:EncryptedKey Id="TK"> <ns0:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" /> <ns0:CipherData> <ns0:CipherValue>SV/7kINewjtWHpy6XvepsVOfcDhx/EEkFkY9uZZEmvg8Fz90OOiuPXPIy7eX395TPnS1anCnNulHcWHVnSBqyb4CeEStJsf3KRD7KanCHJc3T2jaHuqyBumHY8Hut1L29z/daUIFC3SbeYmKmviBwITr2kN6WfqtnQ3XPjrLz9hiWS+4Yh+k7lt0EQX3Osal5bqmfA3V65FYY2IX7vxwI9ZIWW4a7Nfw8EWCEo6X8tN8uN4xs4aKQaisTD6BjRHjsFqLf0i0Tt2oGpqCPuXG/E8rFqrck0PSa6tLxTzxkt80/w0upjI03EzTErVeayIVSPAzmVn3fkoYnqtMGYgL7UHIkcgptb7YZo5e65cxh7vlrcVgRAl8++7FVN9drmQoKJnu2DYWE3LFmbZTyEjQXaVxR3kuQvwyZUjennidG5z/V4HkJtTou738nAZwloS6A3sqHpLRhoUGvtpifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA+T0XMCGfOLVPY6L2iYCeoj9de6DXSgvwHbO2KSmQPfdoJ05+B2oLkwDLAIz6yGMAmk00CwjBe2sJkr4Gz9TTDx9OBRdRjVC/uf0CX2KVwsKFE5apt2YeNq4WE1b8ZRy6NPyZvVdxXjf4FpA0O8G3bdr96xHNmHlHJI57J2kmnUU2IHsOEbk1OSlBsN8=</ns0:CipherValue> </ns0:CipherData> </ns0:EncryptedKey> </Transport_key> </Security> </Header> ,但这没有帮助。

有解决方案吗?

0 个答案:

没有答案