小编kep*_*kis的帖子

如何使用lxml(节点与其他命名空间)添加名称空间前缀?

我需要得到这个xml:

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.or/2003/05/soap-envelope">
   <s:Header>
       <a:Action s:mustUnderstand="1">Action</a:Action>
   </s:Header>
</s:Envelope>
Run Code Online (Sandbox Code Playgroud)

据我所知<Action>节点,它的属性"mustUnderstand"在不同的名称空间下.我现在取得的成就:

from lxml.etree import Element, SubElement, QName, tostring

class XMLNamespaces:
   s = 'http://www.w3.org/2003/05/soap-envelope'
   a = 'http://www.w3.org/2005/08/addressing'


root = Element(QName(XMLNamespaces.s, 'Envelope'), nsmap={'s':XMLNamespaces.s, 'a':XMLNamespaces.a})

header = SubElement(root, QName(XMLNamespaces.s, 'Header'))
action  = SubElement(header, QName(XMLNamespaces.a, 'Action'))
action.attrib['mustUnderstand'] = "1"
action.text = 'Action'

print tostring(root, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

结果:

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
   <s:Header>
      <a:Action mustUnderstand="1">http://schemas.xmlsoap.org/ws/2004/09/transfer/Create</a:Action>
    </s:Header>
</s:Envelope>
Run Code Online (Sandbox Code Playgroud)

我们可以看到,"mustUnderstand"属性前面没有名称空间前缀.那么有可能用lxml 获得" s: mustUnderstand"吗?如果有,那怎么样?

python xml lxml namespaces

3
推荐指数
2
解决办法
4335
查看次数

标签 统计

lxml ×1

namespaces ×1

python ×1

xml ×1