命名空间中的python lxml属性命名空间

时间:2018-10-18 20:30:20

标签: python lxml xml-namespaces

在我正在寻找文件上传的文档中,它在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">

我正在尝试使用lxml.etree库来解决这个问题。

我见过的许多示例都有一个初始名称空间级别的属性,这些属性将使用以下内容覆盖xmlns:xsi部分:

namespace_map = {
        None: persona_namespace,
        'xsi': "http://www.w3.org/2001/XMLSchema-instance"}

但是第二部分xsi:schemaLocation引起了2个问题

1)如何使用lxml完成​​二级名称空间?

2)如何允许名称空间包含空间而不会收到错误(http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd

1 个答案:

答案 0 :(得分:1)

在示例XML中,您有:

要使用lxml构建此元素,您需要使用大括号(James Clark表示法)使用完全限定的名称。

首先定义一个存储名称空间映射的字典:

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

为了构建标准的名称空间,您可以定义前缀:

# tag prefixes
P = '{' + p_url + '}'
XSI = '{' + xsi_url + '}'

然后您可以定义标签名称和属性:

# tag names and attributes
root_tag = P + 'oclcPersonas'
attrs = {
    XSI + 'schemaLocation':
    "http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd"
}

可以如下创建根元素:

# element
root = etree.Element(root_tag, attrib=attrs, nsmap=NS)

您应该拥有自己的元素:

print(etree.tounicode(root))

回答您的问题:

  

2)如何允许名称空间包含空间而不会收到错误(http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd

这不是名称空间,它是schemaLocation属性的值。一个简单的字符串。