首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用lxml在属性中添加命名空间前缀(节点与其他命名空间)?

如何使用lxml在属性中添加命名空间前缀(节点与其他命名空间)?
EN

Stack Overflow用户
提问于 2014-08-05 15:06:17
回答 2查看 7.1K关注 0票数 3

我需要获取这个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>

据我所知,< 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)

和结果:

<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“吗?如果是,那是怎么做的?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25132998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档