简体   繁体   English

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

[英]How to add namespace prefix to attribute with lxml (node is with other namespace)?

I need to get this xml: 我需要得到这个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>

As I understand < Action > node and it's attribute "mustUnderstand" is under different namespaces. 据我所知<Action>节点,它的属性“mustUnderstand”在不同的命名空间下。 What I achieved now: 我现在取得的成就:

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)

And result: 结果:

<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>

As we can see, no namespace prefix in front of "mustUnderstand" attribute. 我们可以看到,“mustUnderstand”属性前面没有名称空间前缀。 So is it possible to get " s: mustUnderstand" with lxml? 那么有可能用lxml获得“ s: mustUnderstand”吗? if yes, then how? 如果有,那怎么样?

只需使用QName,就像使用元素名称一样:

action.attrib[QName(XMLNamespaces.s, 'mustUnderstand')] = "1"

Also if you want to create all attributes in single SubElement sentence, you can exploit its feature that attributes are just a dictionary: 此外,如果要在单个SubElement语句中创建所有属性,可以利用其属性只是字典的功能:

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

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'), attrib={
    'notUnderstand':'1',
    QName(XMLNamespaces.s, 'mustUnderstand'):'1'
    })

print (tounicode(root, pretty_print=True))

The result is: 结果是:

<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 notUnderstand="1" s:mustUnderstand="1"/>
  </s:Header>
</s:Envelope>

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

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