Skip to main content
 首页 » 编程设计

python之lxml之类型错误 : write() got an unexpected keyword argument 'default_namespace'

2025年02月15日7mfryf

下面是一个最小的工作示例。我已经使用 Python 3.4、Python 3.6 32 位和 Python 3.6 64 位对此进行了测试。

import io 
from lxml import etree 
 
test_node = etree.fromstring(''' 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-trust/200512"> 
  <soap:Body> 
     <ns1:RequestSecurityToken/> 
  </soap:Body> 
</soap:Envelope>''') 
output = io.BytesIO(b'<?xml version="1.0" encoding="UTF-8"?>') 
test_node.getroottree().write(output, 
                         encoding="UTF-8", 
                         xml_declaration=None, 
                         default_namespace=None, 
                         method="c14n", 
                         short_empty_elements=False 
                         ) 
output.seek(0) 
print(output.read()) 

结果:

Traceback (most recent call last): 
  File "C:/not_telling/c14n.py", line 16, in <module> 
    short_empty_elements=False 
  File "lxml.etree.pyx", line 1869, in lxml.etree._ElementTree.write (src\lxml\lxml.etree.c:57004) 
TypeError: write() got an unexpected keyword argument 'short_empty_elements' 

我刚刚将 lxml 版本升级到 4.0.0。 (但同样是 3.7 的问题。)

我需要使用 C14N 方法导出,并且(虽然未包含在示例中)我还需要指定需要出现在生成的规范形式中的命名空间列表。例如。我也必须使用 inclusive_ns_prefixes 参数。

更新:实际上,这似乎是 Python 内置 xml 模块的问题,而不是 lxml。

这是我调用的方法:

https://github.com/python/cpython/blob/master/Lib/xml/etree/ElementTree.py#L721

它确实有一个 short_empty_elements 参数,但它不接受它。

请您参考如下方法:

lxml 中的_ElementTree.write() 方法不支持default_namespace 和short_empty_elements 参数。参见 http://lxml.de/api/lxml.etree._ElementTree-class.html#write .

但是,从 Python 3.4 开始,这两个参数在 ElementTree 标准模块中可用。参见 https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write .