如何在lxml中的属性中添加名称空间 [英] How to add a namespace to an attribute in lxml

查看:115
本文介绍了如何在lxml中的属性中添加名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python和lxml创建一个看起来像这样的xml条目:

I'm trying to create an xml entry that looks like this using python and lxml:

<resource href="Unit 4.html" adlcp:scormtype="sco">

我正在使用python和lxml.我在adlcp:scormtype属性上遇到麻烦.我是xml的新手,所以如果我输入错误,请更正我. adlcp是名称空间,scormtype是在adlcp名称空间中定义的属性,对吗?
我什至不确定这是否是正确的问题,但是...我的问题是,如何使用lxml从非默认名称空间向元素添加属性?如果这是一个琐碎的问题,我事先表示歉意.

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.

推荐答案

这不是完整的答复,而只是一些指针.

This is not a full reply but just a few pointers.

adlcp不是名称空间,它是名称空间前缀.命名空间在文档中是由xmlns:adlcp="http://xxx/yy/zzz"

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"

在lxml中,您总是设置一个元素/属性名称,包括名称空间,例如 {http://xxx/yy/zzz}scormtype而不是scormtype.然后,lxml将自动放入名称空间前缀. 但是,lxml会将前缀设置为ns0或类似名称,除非您进行更多的摆弄,但这应该足够,因为前缀并不代表任何含义. (但是,有些人更喜欢控制前缀名称;请参见Element和SubElement函数以及register_namespace函数的nsmap参数.)

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教程,以及 查看全文

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