繁体   English   中英

如何用LXML编写命名空间元素属性?

[英]How to write namespaced element attributes with LXML?

我正在使用lxml(2.2.8)来创建和编写一些XML(特别是XGMML)。 将要阅读它的应用程序显然相当挑剔,并希望看到一个顶级元素:

<graph label="Test" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="h
ttp://www.w3.org/1999/xlink" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-
ns#" xmlns:cy="http://www.cytoscape.org" xmlns="http://www.cs.rpi.edu/XGMML"  di
rected="1">

如何使用lxml设置这些xmlns:属性? 如果我尝试明显的

root.attrib['xmlns:dc']='http://purl.org/dc/elements/1.1/'
root.attrib['xmlns:xlink']='http://www.w3.org/1999/xlink'
root.attrib['xmlns:rdf']='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
root.attrib['xmlns:cy']='http://www.cytoscape.org'
root.attrib['xmlns']='http://www.cs.rpi.edu/XGMML'

lxml抛出一个ValueError: Invalid attribute name u'xmlns:dc'

我过去曾经使用过很多XML和lxml来处理简单的事情,但是到目前为止还是设法避免需要知道关于命名空间的任何事情。

与允许这样的ElementTree或其他序列化程序不同, lxml需要您事先设置这些名称空间:

NSMAP = {"dc" : 'http://purl.org/dc/elements/1.1',
         "xlink" : 'http://www.w3.org/1999/xlink'}

root = Element("graph", nsmap = NSMAP)

(以及其他声明等等)

然后您可以使用适当的声明来使用命名空间:

n = SubElement(root, "{http://purl.org/dc/elements/1.1}foo")

当然,输入会很烦人,因此将路径分配给短常量名称通常是有益的:

DCNS = "http://purl.org/dc/elements/1.1"

然后在NSMAPSubElement声明中使用该变量:

n = SubElement(root, "{%s}foo" % (DCNS))

使用ElementMaker

import lxml.etree as ET
import lxml.builder as builder
E = builder.ElementMaker(namespace='http://www.cs.rpi.edu/XGMML',
                         nsmap={None: 'http://www.cs.rpi.edu/XGMML',
                         'dc': 'http://purl.org/dc/elements/1.1/',
                         'xlink': 'http://www.w3.org/1999/xlink',
                         'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
                         'cy': 'http://www.cytoscape.org', })
graph = E.graph(label="Test", directed="1")
print(ET.tostring(graph, pretty_print=True))

产量

<graph xmlns:cy="http://www.cytoscape.org" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.cs.rpi.edu/XGMML" directed="1" label="Test"/>

暂无
暂无

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

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