如何在Python的xml.dom.minidom中设置元素的id?
怎样做?创建了一个文档和一个元素:
import xml.dom.minidom as d
a=d.Document()
b=a.createElement('test')
setIdAttribute 不起作用:(
b.setIdAttribute('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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
如果我手动设置它, getElementById 找不到它。
b.setAttribute('id', 'something')
a.getElementById('something')
我必须做什么?
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 "<stdin>", line 1, in <module>
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有两件事是错误的。
Document.getElementById
只会查找文档中实际存在的元素。在这里,您创建了b
但实际上并未将其添加到文档中。 (这在 JavaScript 中是完全相同的。)您必须使用
setIdAttribute
将id
标记为 ID 属性。 (在 JavaScript 中不需要这样做,因为在 HTML 文档中,名为id
的属性会自动被视为 ID 属性,这在逻辑上是足够的。但是 XML 不会自动处理名为id 的属性
id
作为 ID;您可以显式声明它们在您的 DTD 中,也可以为每个 ID 属性单独调用setIdAttribute
我不确定 DTD 是否适用于 minidom。 ,这不是完整的 DOM 实现。)就像这样:
之后,
getElementById
工作:Two things are wrong here.
Document.getElementById
will only find elements that are actually in the document. Here you've createdb
but not actually added it to the document. (It's exactly the same in JavaScript.)You have to mark
id
as an ID attribute usingsetIdAttribute
. (There's no need to do this in JavaScript because in HTML documents, attributes namedid
are automatically considered to be ID attributes, logically enough. But XML does not automatically treat attributes namedid
as IDs; you can either explicitly declare that they are in your DTD or callsetIdAttribute
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:
After that,
getElementById
works:将 id 属性的名称添加到 DTD 应该会有所帮助。例如,如果您希望每个元素都将
id
设置为所有元素的 id 属性,则可以按如下方式设置 DTD:
< ;!DOCTYPE div []>
这是一个工作示例:
Adding the name of the id attribute to the DTD should help. For example, if you want every to set the
id
as the id attribute for all<div>
elements, you can set up your DTD as follows:<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]>
This is a working example:
有时,对文档中的每个元素执行此操作的最简单方法是解析完整的 DOM,如下所示:
Sometimes, the easiest way to do this for each element in the document is to parse the full DOM once like this :