如何在Python的xml.dom.minidom中设置元素的id? [英] How to set element's id in Python's xml.dom.minidom?

查看:886
本文介绍了如何在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不工作:(<

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

如果我手动设置,getElementById找不到。

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

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

我要做什么?

推荐答案

这里有两件事情是错误的。

Two things are wrong here.


  1. Document.getElementById 只会找到文档中实际的元素。在这里,您创建了 b ,但实际上并未将其添加到文档中。 (在JavaScript中完全一样。)

  1. 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.)

您必须将 id 标记为ID属性 setIdAttribute 。 (JavaScript不需要这样做,因为在HTML文档中,名为 id 的属性在逻辑上足够自动被认为是ID属性,但是XML不自动将名为 id 的属性自动处理为ID;您可以明确声明它们在您的DTD中,也可以调用 setIdAttribute 单独为每个ID属性,而且我不知道DTD的东西将与minidom一起使用,这不是一个完整的DOM实现。)

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.)

像这样:

import xml.dom.minidom as d
a = d.Document()
b = a.createElement('test')
a.appendChild(b)
b.setAttribute('id', 'x')
b.setIdAttribute('id')

之后, getElementById 的作品: / p>

After that, getElementById works:

>>> a.getElementById('x')
<DOM Element: test at 0xb77712ec>

这篇关于如何在Python的xml.dom.minidom中设置元素的id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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