在我查看的文件上传文档中,它需要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中出现了两个问题
1)如何使用lxml完成二级命名空间?
2)如何允许命名空间包含一个空格而不接收错误(http://worldcat.org/xmlschemas/IDMPersonas-2.2 IDMPersonas-2.2.xsd)
发布于 2018-10-18 21:28:51
在示例XML中,您有:
oclcPersonas,要用lxml构建这个元素,您需要使用大括号(James符号)使用完全限定的名称。
首先,定义一个存储名称空间映射的字典:
# 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属性的值。一根简单的绳子。
https://stackoverflow.com/questions/52882082
复制相似问题