如何在python中从xml中删除ns?

2024-09-29 01:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个xml:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:epp xmlns:ns0="urn:ietf:params:xml:ns:epp-1.0" 
 xmlns:ns1="http://epp.nic.ir/ns/contact-1.0">
   <ns0:command>
      <ns0:check>
         <ns1:check>
            <ns1:id>ex61-irnic</ns1:id>
            <ns1:id>ex999-irnic</ns1:id>
            <ns1:authInfo>
               <ns1:pw>1487441516170712</ns1:pw>
            </ns1:authInfo>
         </ns1:check>
      </ns0:check>
      <ns0:clTRID>TEST-12345</ns0:clTRID>
   </ns0:command>
</ns0:epp>

我想用python 3将它改成这样:

^{pr2}$

我试着用对象化。取消注释来自lxml模块。 但没用。 你能帮我达到目的吗?在


Tags: idversioncheckxmlcommandencodingnspw
2条回答

考虑一下XSLT,这是一种专门用来转换XML文件的语言,比如删除名称空间。Python的第三方模块lxml,可以运行xslt1.0脚本。因为XSLT脚本是XML文件,所以可以像任何XML一样从文件或字符串进行解析。不需要循环或条件if逻辑。此外,您还可以在其他语言(PHP、Java、C#等)中使用这个XSLT脚本

XSLT(另存为.xsl文件,在Python中引用)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <!  IDENTITY TRANSFROM: COPY DOC AS IS  >
  <xsl:template match="@*|node()">
    <xsl:copy>    
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!  REMOVE NAMESPACE PREFIXES, ADD DOC NAMESPACE  >
  <xsl:template match="*">
    <xsl:element name="{local-name()}" namespace="urn:ietf:params:xml:ns:epp-1.0">    
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Python

^{pr2}$

输出

<?xml version="1.0"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
  <command>
    <check>
      <check>
        <id>ex61-irnic</id>
        <id>ex999-irnic</id>
        <authInfo>
          <pw>1487441516170712</pw>
        </authInfo>
      </check>
    </check>
    <clTRID>TEST-12345</clTRID>
  </command>
</epp>

{a2是一个名称空间的组合,显示了如何修改^的名称空间。在

代码有点粗糙(我特别怀疑使用_setroot方法是否符合犹太教规),但它似乎有效:

from lxml import etree

inputfile = 'data.xml'
target_ns = 'urn:ietf:params:xml:ns:epp-1.0'
nsmap = {None: target_ns}

tree = etree.parse(inputfile)
root = tree.getroot()

# here we set the namespace of all elements to target_ns
for elem in root.getiterator():
    tag = etree.QName(elem.tag)
    elem.tag = '{%s}%s' % (target_ns, tag.localname)

# create a new root element and set the namespace map, then
# copy over all the child elements    
new_root = etree.Element(root.tag, nsmap=nsmap)
new_root[:] = root[:]

# create a new elementtree with new_root so that we can use the
# .write method.
tree = etree.ElementTree()
tree._setroot(new_root)

tree.write('done.xml',
           pretty_print=True, xml_declaration=True, encoding='UTF-8')

给定示例输入,将在done.xml中生成:

^{pr2}$

相关问题 更多 >