简体   繁体   English

如何使用lxml在XML元素名称中使用“:”?

[英]How do I use “:” in XML element names using lxml?

How do I generate and parse XML like the following using lxml ? 如何使用lxml生成和解析XML,如下所示?

<s:Envelope xmlns:s="a" xmlns:a="http_//www.w3.org/2005/08/addressing">
....
</s:Envelope>

I currently swap : with _ in the element names when I parse and generate XML, but it seems stupid. 我目前在解析并生成XML时在元素名称中用_交换了:,但这似乎很愚蠢。

It's not clear exactly what you're asking, but maybe this will help: 不清楚您要问的是什么,但这也许会有所帮助:

An element such as <s:Envelope> is using a XML namespace prefix. 诸如<s:Envelope>类的元素正在使用XML名称空间前缀。 This is used to indicate that the s:Envelope attribute in this document is defined in the a namespace. 这是用来指示该s:Envelope本文件中的属性在被定义a命名空间。

LXML represents XML namespaces using a namespace prefix in braces, for example: {a}Envelope . LXML使用大括号中的名称空间前缀表示XML名称空间,例如: {a}Envelope Your example document is sort of confusing, because you also defined the a: namespace prefix, so: 您的示例文档有点令人困惑,因为您还定义了a:名称空间前缀,所以:

  • a:Element is equivalent to {http://www.w3.org/2005/08/addressing}Element , and a:Element等效于{http://www.w3.org/2005/08/addressing}Element ,并且
  • s:Element is equivalent to {a}Element . s:Element等效于{a}Element

Many of the LXML commands let you provide a namespace prefix mapping. 许多LXML命令使您可以提供名称空间前缀映射。 For example, to find the Envelope element in your document using XPATH, you could do this: 例如,要使用XPATH在文档中查找Envelope元素,可以执行以下操作:

import lxml.etree as etree
doc = etree.parse('mydocument.xml')
envelope = doc.xpath('//s:Envelope',
  namespaces={'s': 'a'})

Note that this is exactly equivalent to: 请注意,这完全等同于:

envelope = doc.xpath('//x:Envelope',
  namespaces={'x': 'a'})

That is, the namespace prefix doesn't have to match what is used in the source XML document; 也就是说,名称空间前缀不必与源XML文档中使用的名称匹配。 only the the absolute namespace matters. 只有绝对名称空间很重要。

You can read more about LXML and namespaces here . 您可以在此处阅读有关LXML和名称空间的更多信息。

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

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