简体   繁体   English

使用ElementTree在Python 3中处理XML命名空间

[英]XML Namespace handling in Python 3 with ElementTree

I have an input XML coming with some wrong namespaces. 我有一个带有一些错误名称空间的输入XML。 I tried to fix them with ElementTree but without success 我试图用ElementTree修复它们,但没有成功

Example input: (here ns0: can be ns:, p:, n: etc etc... ) 输入示例:(此处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>

Output file needed: (namespace in the root must be without prefix and some inner tags declared as xmlns="") 所需的输出文件:(根目录中的命名空间必须没有前缀,并且某些内部标记声明为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>

I tried to change root namespace as below, but the resulting file is unchanged 我尝试如下更改根名称空间,但生成的文件未更改

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)

Instead when trying with 相反,当尝试

changing root.tag  = 'Invoice'

it produces a tag without namespace at all 它产生一个根本没有名称空间的标签

Please let me know whether I'm making any mistake or I should switch to another library or try with a string replace with regex 请让我知道我是否在犯任何错误,还是应该切换到另一个库,或者尝试用正则表达式替换字符串

Thanks in advance 提前致谢

Don't now if it can be useful to anyone but I managed to fix namespaces using lxml and the following code. 现在不要对其他人有用,但我设法使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM