相关疑难解决方法(0)

如何在lxml中为属性添加命名空间

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

<resource href="Unit 4.html" adlcp:scormtype="sco">
Run Code Online (Sandbox Code Playgroud)

我正在使用python和lxml.我遇到了adlcp:scormtype属性问题.我是xml的新手,所以如果我错了请纠正我. adlcp是一个名称空间,scormtype是一个在adlcp名称空间中定义的属性,对吧?
我甚至不确定这是否是正确的问题但是...我的问题是,如何使用lxml从非默认命名空间向元素添加属性?如果这是一个微不足道的问题,我会提前道歉.

python xml lxml scorm

13
推荐指数
2
解决办法
1万
查看次数

lxml ElementMaker 属性格式

感谢这个问题/答案,我能够将命名空间属性添加到根元素中。所以现在我有这个:

代码

from lxml.builder import ElementMaker

foo = 'http://www.foo.org/XMLSchema/bar'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
E = ElementMaker(namespace=foo, nsmap={'foo': foo, 'xsi': xsi})

fooroot = E.component()
fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)] = 'http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd'
bars = E.bars(label='why?', validates='required')
fooroot.append(bars)
bars.append(E.bar(label='Image1'))
bars.append(E.bar(label='Image2'))

etree.dump(fooroot)
Run Code Online (Sandbox Code Playgroud)

这给了我想要的输出:

输出

<foo:component xmlns:foo="http://www.foo.org/XMLSchema/bar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.foo.org/XMLSchema/bar http://www.foo.org/XMLSchema/barindex.xsd">
  <foo:bars label="why?" validates="required">
    <foo:bar label="Image1"/>
    <foo:bar label="Image2"/>
  </foo:bars>
</foo:component>
Run Code Online (Sandbox Code Playgroud)

问题

为什么fooroot.attrib['{{{pre}}}schemaLocation'.format(pre=xsi)]pre 周围需要 3 个大括号?

1 个大括号:{pre}导致 ValueError BAD
2 个大括号:在输出上{{pre}}产生BAD 3 个大括号:在输出上产生GOODns0:schemaLocation
{{{pre}}}xsi:schemaLocation

我了解.format该字符串的用法,但我想了解为什么需要 3 …

python attributes lxml

3
推荐指数
1
解决办法
1503
查看次数

标签 统计

lxml ×2

python ×2

attributes ×1

scorm ×1

xml ×1