为什么xml.etree.ElementTree.parse以小写形式转换名称空间元素

时间:2016-08-20 00:04:54

标签: python xml xml.etree

我想指示ET.parse将命名空间大小写保留在XML中,因为它是

import xml.etree.ElementTree as ET
tree = ET.parse("mimeTypes.rdf")
ET.dump(tree)
<rdf:RDF xmlns:ns1="http://home.netscape.com/NC-rdf#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description ns1:value="irc" rdf:about="urn:scheme:irc">
    <ns1:handlerProp rdf:resource="urn:scheme:handler:irc" />
  </rdf:Description>
  <rdf:Description ns1:value="application/pdf" rdf:about="urn:mimetype:application/pdf">
    <ns1:handlerProp rdf:resource="urn:mimetype:handler:application/pdf" />
  </rdf:Description>

原始文件如下所示:

<?xml version="1.0"?>
<RDF:RDF xmlns:NC="http://home.netscape.com/NC-rdf#"
         xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <RDF:Description RDF:about="urn:scheme:irc"
                   NC:value="irc">
    <NC:handlerProp RDF:resource="urn:scheme:handler:irc"/>
  </RDF:Description>
  <RDF:Description RDF:about="urn:mimetype:application/pdf"
                   NC:value="application/pdf">
    <NC:handlerProp RDF:resource="urn:mimetype:handler:application/pdf"/>
  </RDF:Description>

1 个答案:

答案 0 :(得分:0)

显然我必须注册XML中使用的命名空间:

 import xml.etree.ElementTree as ET
 tree = ET.parse("mimeTypes.rdf")
 et.register_namespace('NC', 'http://home.netscape.com/NC-rdf#')
 et.register_namespace('RDF', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
 tree.write("tmp.xml", xml_declaration=True, encoding='utf-8', method="xml")