【问题标题】:How to add namespace prefix to attribute with lxml (node is with other namespace)?如何使用 lxml 将命名空间前缀添加到属性(节点与其他命名空间一起)?
【发布时间】:2014-08-05 07:06:16
【问题描述】:

我需要得到这个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>

据我了解 节点,它的属性“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)

结果:

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

我们可以看到,“mustUnderstand”属性前面没有命名空间前缀。那么有没有可能用lxml得到“s: mustUnderstand”呢?如果是,那么如何?

【问题讨论】:

    标签: python xml namespaces lxml


    【解决方案1】:

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

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

    【讨论】:

    • 这很好:)。谢谢!
    【解决方案2】:

    另外,如果你想在单个子元素语句中创建所有属性,你可以利用它的特性只是一个字典:

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

    结果是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多