【问题标题】:XML Namespace handling in Python 3 with ElementTree在 Python 3 中使用 ElementTree 处理 XML 命名空间
【发布时间】:2019-02-08 10:59:16
【问题描述】:

我的输入 XML 带有一些错误的命名空间。我试图用 ElementTree 修复它们但没有成功

示例输入:(这里ns0:可以是ns:、p:、n:等...)

<ns0:Invoice xmlns:ns0="http://invoices.com/docs/xsd/invoices/v1.2" version="FPR12">

  <InvoiceHeader>
    <DataH>data header</DataH>
  </InvoiceHeader>

  <InvoiceBody>
    <DataB>data body</DataB>
  </InvoiceBody>

</ns0:Invoice>

需要的输出文件:(根中的命名空间必须没有前缀,并且一些内部标签声明为 xmlns="")

<Invoice xmlns:"http://invoices.com/docs/xsd/invoices/v1.2" version="FPR12">

  <InvoiceHeader xmlns="">
    <DataH>data header</DataH>
  </InvoiceHeader>

  <InvoiceBody xmlns="">
    <DataB>data body</DataB>
  </InvoiceBody>

</Invoice>

我尝试如下更改根命名空间,但生成的文件没有改变

import xml.etree.ElementTree as ET

tree = ET.parse('./cache/test.xml')
root = tree.getroot()

root.tag = '{http://invoices.com/docs/xsd/invoices/v1.2}Invoice'
xml = ET.tostring(root, encoding="unicode")
with open('./cache/output.xml', 'wt') as f:
    f.write(xml)

而是在尝试使用时

changing root.tag  = 'Invoice'

它产生一个完全没有命名空间的标签

请让我知道我是否犯了任何错误,或者我应该切换到另一个库或尝试用正则表达式替换字符串

提前致谢

【问题讨论】:

    标签: python xml


    【解决方案1】:

    如果它对任何人都有用,现在不要这样做,但我设法使用 lxml 和以下代码修复了命名空间。

    from lxml import etree
    from copy import deepcopy
    
    tree = etree.parse('./cache/test.xml')
    
    # create a new root without prefix in the namespace
    NSMAP = {None : "http://invoices.com/docs/xsd/invoices/v1.2"}
    root = etree.Element("{http://invoices.com/docs/xsd/invoices/v1.2}Invoice", nsmap = NSMAP)
    
    # copy attributes from original root
    for attr, value in tree.getroot().items():
        root.set(attr,value)
    
    # deep copy of children (adding empty namespace in some tags)
    for child in tree.getroot().getchildren():
        if child.tag in( 'InvoiceHeader', 'InvoiceBody'):
            child.set("xmlns","")
        root.append( deepcopy(child) )
    
    xml = etree.tostring(root, pretty_print=True)
    with open('./cache/output.xml', 'wb') as f:
        f.write(xml)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-17
      • 2018-09-12
      • 1970-01-01
      • 2017-07-08
      • 2013-01-28
      相关资源
      最近更新 更多