python中minidom添加子节点,如何在Python的xml.dom.minidom中设置元素的id?

How to? Created a document and an element:

import xml.dom.minidom as d

a=d.Document()

b=a.createElement('test')

setIdAttribute doesn't work :(

b.setIdAttribute('something')

Traceback (most recent call last):

File "", line 1, in

File "/usr/lib/python2.6/xml/dom/minidom.py", line 835, in setIdAttribute

self.setIdAttributeNode(idAttr)

File "/usr/lib/python2.6/xml/dom/minidom.py", line 843, in setIdAttributeNode

raise xml.dom.NotFoundErr()

xml.dom.NotFoundErr

And if I set this by hand, getElementById can't find it.

b.setAttribute('id', 'something')

a.getElementById('something')

What I have to do?

解决方案

Two things are wrong here.

Document.getElementById will only find elements that are actually in the document. Here you've created b but not actually added it to the document. (It's exactly the same in JavaScript.)

You have to mark id as an ID attribute using setIdAttribute. (There's no need to do this in JavaScript because in HTML documents, attributes named id are automatically considered to be ID attributes, logically enough. But XML does not automatically treat attributes named id as IDs; you can either explicitly declare that they are in your DTD or call setIdAttribute individually for every ID attribute. And I am not sure the DTD thing will work with minidom, which is not a full DOM implementation.)

Like so:

import xml.dom.minidom as d

a = d.Document()

b = a.createElement('test')

a.appendChild(b)

b.setAttribute('id', 'x')

b.setIdAttribute('id')

After that, getElementById works:

>>> a.getElementById('x')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值