如何使用lxml向属性添加名称空间前缀(节点与其他名称空间相同)? [英] How to add namespace prefix to attribute with lxml (node is with other namespace)?

查看:65
本文介绍了如何使用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>

据我了解<动作>节点,其属性"mustUnderstand"位于不同的命名空间下.我现在所取得的成就:

As I understand < Action > node and it's attribute "mustUnderstand" is under different namespaces. 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)

结果:

<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"?如果是,那怎么办?

As we can see, no namespace prefix in front of "mustUnderstand" attribute. So is it possible to get "s: mustUnderstand" with lxml? if yes, then how?

推荐答案

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

Just use QName, like you do with element names:

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

这篇关于如何使用lxml向属性添加名称空间前缀(节点与其他名称空间相同)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆