How to set element's id in Python's xml.dom.minidom?

旧时模样 提交于 2019-12-04 14:40:56

问题


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?


回答1:


Two things are wrong here.

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

  2. 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')
<DOM Element: test at 0xb77712ec>



回答2:


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:

>>> from xml.dom.minidom import parse, parseString                              
>>> data='<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]><div><div id="foo">FOO word</div><div id="bar">BAR word</div></div>'
>>> x=parseString(data)
>>> x.getElementById('foo')
<DOM Element: div at 0x1126440>
>>> x.getElementById('foo').toxml()
u'<div id="foo">FOO word</div>'


来源:https://stackoverflow.com/questions/1971186/how-to-set-elements-id-in-pythons-xml-dom-minidom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!