[英]python lxml attribute namespaces within namespaces
In the documentation I'm looking at for a file upload, it needs this specific tag at the beginning of the xml file: 在我正在寻找文件上传的文档中,它在xml文件的开头需要这个特定的标记:
<oclcPersonas xmlns="http://worldcat.org/xmlschemas/IDMPersonas-2.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd">
I'm trying to use the lxml.etree library to figure this out. 我正在尝试使用lxml.etree库来解决这个问题。
Many of the examples I've seen have a initial level of namespace for attributes that would cover the xmlns:xsi
portion using this: 我见过的许多示例都具有用于属性的初始名称空间级别,这些属性将使用以下内容覆盖
xmlns:xsi
部分:
namespace_map = {
None: persona_namespace,
'xsi': "http://www.w3.org/2001/XMLSchema-instance"}
but 2 questions arise from the second portion xsi:schemaLocation
但是第二部分
xsi:schemaLocation
引起2个问题
1) How would I accomplish a secondary level of namespace using lxml? 1)如何使用lxml完成二级名称空间?
2) How do I allow the namespaces to contain a space without receiving an error ( http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd
) 2)如何在不接收错误的情况下允许名称空间包含空间(
http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd
)
In your sample XML, you have : 在示例XML中,您有:
oclcPersonas
in the default namespace, oclcPersonas
, To build this element with lxml, you need to use the fully-qualified name using curly braces (James Clark notation). 要使用lxml构建此元素,您需要使用大括号(James Clark表示法)使用完全限定的名称。
First define a dictionary which store your namespace mapping: 首先定义一个字典,用于存储您的名称空间映射:
# your namespaces
p_url = "http://worldcat.org/xmlschemas/IDMPersonas-2.2"
xsi_url = "http://www.w3.org/2001/XMLSchema-instance"
NS = {None: p_url, 'xsi': xsi_url}
In order to build fully-qualified namespace, you can define prefixes: 为了构建标准的名称空间,您可以定义前缀:
# tag prefixes
P = '{' + p_url + '}'
XSI = '{' + xsi_url + '}'
Then you can define the tag names and attributes: 然后,您可以定义标签名称和属性:
# tag names and attributes
root_tag = P + 'oclcPersonas'
attrs = {
XSI + 'schemaLocation':
"http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd"
}
The root element can be created like below: 可以如下创建根元素:
# element
root = etree.Element(root_tag, attrib=attrs, nsmap=NS)
You should have your element: 您应该具有以下元素:
print(etree.tounicode(root))
To answer your question: 要回答您的问题:
2) How do I allow the namespaces to contain a space without receiving an error (
http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd
)2)如何在不接收错误的情况下允许名称空间包含空间(
http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd
)
This is not a namespace, this is the value of the schemaLocation
attribute. 这不是名称空间,这是
schemaLocation
属性的值。 A simple string. 一个简单的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.