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

后端 未结 2 504
無奈伤痛
無奈伤痛 2020-12-30 17:35

How to? Created a document and an element:

import xml.dom.minidom as d
a=d.Document()
b=a.createElement(\'test\')

setIdAttribute doesn\'t w

2条回答
  •  渐次进展
    2020-12-30 17:54

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

提交回复
热议问题