python 如何将命名空间添加到 lxml 中的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1374443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a namespace to an attribute in lxml
提问by Mateo
I'm trying to create an xml entry that looks like this using python and lxml:
我正在尝试使用 python 和 lxml 创建一个如下所示的 xml 条目:
<resource href="Unit 4.html" adlcp:scormtype="sco">
I'm using python and lxml. I'm having trouble with the adlcp:scormtype
attribute. I'm new to xml so please correct me if I'm wrong. adlcp
is a namespace and scormtype
is an attribute that is defined in the adlcp namespace, right?
I'm not even sure if this is the right question but... My question is, how do I add an attribute to an element from a non-default namespace using lxml? I apologize in advance if this is a trivial question.
我正在使用 python 和 lxml。我的adlcp:scormtype
属性有问题。我是 xml 的新手,所以如果我错了,请纠正我。 adlcp
是命名空间并且scormtype
是在 adlcp 命名空间中定义的属性,对吗?
我什至不确定这是否是正确的问题,但是...我的问题是,如何使用 lxml 从非默认命名空间向元素添加属性?如果这是一个微不足道的问题,我提前道歉。
回答by user151019
This is not a full reply but just a few pointers.
这不是一个完整的答复,只是一些提示。
adlcp is not the namespace it is a namespace prefix. The namespace is defined in the document by an attribute like xmlns:adlcp="http://xxx/yy/zzz"
adlcp 不是命名空间,而是命名空间前缀。命名空间由文档中的属性定义,如xmlns:adlcp="http://xxx/yy/zzz"
In lxml you always set an element/attribute name including the namespace e.g.
{http://xxx/yy/zzz}scormtype
instead of just scormtype. lxml will then put in a namespace prefix automatically.
However lxml will set the prefix to ns0 or similar unless you do more fiddling but that should be sufficient as the prefix does not mean anything. (However some people prefer controlling the prefix name; see the nsmap argument on the Element and SubElement functions, and the register_namespace function).
在 lxml 中,您总是设置一个元素/属性名称,包括命名空间,例如,
{http://xxx/yy/zzz}scormtype
而不仅仅是 scormtype。然后 lxml 将自动放入命名空间前缀。但是 lxml 会将前缀设置为 ns0 或类似的,除非你做更多的摆弄,但这应该足够了,因为前缀并不意味着什么。(但是,有些人更喜欢控制前缀名称;请参阅 Element 和 SubElement 函数上的 nsmap 参数,以及 register_namespace 函数)。
I would look at the lxml tutorial on namespaceand also Dive into Python - XML chapter
回答by user4456183
Try this:
试试这个:
builder = ElementMaker(namespace="http://a.different.url/blah/v.10",
nsmap={
'adlcp': "http://a.namespace.url/blah/v.10",
'anotherns': "http://a.different.url/blah/v.10"
})
builder.resource()
builder.attrib['href'] = "Unit 4.html"
builder.attrib['{http://a.namespace.url/blah/v.10}scormtype'] = 'sco'
print(etree.tostring(builder, pretty_print=True))