如何使用LXML编写命名空间元素属性? [英] How to write namespaced element attributes with LXML?

查看:86
本文介绍了如何使用LXML编写命名空间元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用lxml(2.2.8)创建和写出一些XML(特别是XGMML).应用(正在阅读)显然很 fussy,并希望看到带有以下内容的顶级元素:

I'm using lxml (2.2.8) to create and write out some XML (specifically XGMML). The app which will be reading it is apparently fairly fussy and wants to see a top level element with:

<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:属性?如果我尝试显而易见的

How do I setup those xmlns: attributes with lxml ? If I try the obvious

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:无效的属性名称u'xmlns:dc'

过去,对于简单的东西,我已经大量使用了XML和lxml,但是到目前为止,设法避免了对名称空间的任何了解.

I've used XML and lxml a fair amount in the past for simple stuff, but managed to avoid needing to know anything about namespaces so far.

推荐答案

与ElementTree或其他允许此操作的序列化程序不同, lxml 需要您事先设置以下名称空间:

Unlike ElementTree or other serializers that would allow this, lxml needs you to set up these namespaces beforehand:

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

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

(其余的声明依此类推)

(and so on and so forth for the rest of the declarations)

然后你可以使用命名空间的正确声明:

And then you can use the namespaces using their proper declarations:

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

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

Of course this gets annoying to type, so it is generally beneficial to assign the paths to short constant names:

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

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

And then use that variable in both the NSMAP and the SubElement declarations:

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

这篇关于如何使用LXML编写命名空间元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆