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

名称空间中的python lxml属性名称空间,python,lxml,xml-namespaces,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.xs

在我正在查看的文件上载文档中,它需要在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">
但是第二部分xsi中出现了两个问题:schemaLocation

1如何使用lxml实现二级命名空间


2如何允许名称空间包含空间而不接收错误http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd在示例XML中,您有:

默认命名空间中的根元素oclcPersonas, 默认命名空间:, “xsi”命名空间:, “xsi”命名空间中的“schemaLocation”属性。 要使用lxml构建此元素,需要使用带花括号的完全限定名

首先定义存储命名空间映射的字典:

# 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属性的值。一个简单的字符串。

非常感谢!工作完美
print(etree.tounicode(root))