2009-12-30 20 views

risposta

11

Non si dovrebbe istanziare le classi da minidom direttamente. Non è una parte supportata dell'API, gli ownerDocument non si legano e puoi ottenere strani comportamenti scorretti. Invece utilizzare i metodi Livello DOM 2 core corrette:

>>> imp= minidom.getDOMImplementation('') 
>>> dt= imp.createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd') 

('DTD/xhtml1-strict.dtd' è un comunemente usato ma sbagliato SystemId Questa relativa URL sarebbe solo valido all'interno della cartella XHTML1 a w3.. org.)

Ora hai un nodo DocumentType, è possibile aggiungerlo a un documento. Secondo lo standard, l'unico modo garantito per farlo è in fase di creazione di documenti:

>>> doc= imp.createDocument('http://www.w3.org/1999/xhtml', 'html', dt) 
>>> print doc.toxml() 
<?xml version="1.0" ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html/> 

Se si desidera cambiare il doctype di un documento esistente, che è più problemi. Lo standard DOM non richiede che i nodi DocumentType senza ownerDocument siano inseribili in un documento. Tuttavia alcuni DOM lo permettono, ad es. pxdom. minidom tipo di esso permette:

>>> doc= minidom.parseString('<html xmlns="http://www.w3.org/1999/xhtml"><head/><body/></html>') 
>>> dt= minidom.getDOMImplementation('').createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd') 
>>> doc.insertBefore(dt, doc.documentElement) 
<xml.dom.minidom.DocumentType instance> 
>>> print doc.toxml() 
<?xml version="1.0" ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'><html xmlns="http://www.w3.org/1999/xhtml"><head/><body/></html> 

ma con gli insetti:

>>> doc.doctype 
# None 
>>> dt.ownerDocument 
# None 

, che può o non può importa a voi.

Tecnicamente, l'unico modo affidabile per lo standard per impostare un doctype su un documento esistente è quello di creare un nuovo documento e importare l'intero vecchio documento in esso!

def setDoctype(document, doctype): 
    imp= document.implementation 
    newdocument= imp.createDocument(doctype.namespaceURI, doctype.name, doctype) 
    newdocument.xmlVersion= document.xmlVersion 
    refel= newdocument.documentElement 
    for child in document.childNodes: 
     if child.nodeType==child.ELEMENT_NODE: 
      newdocument.replaceChild(
       newdocument.importNode(child, True), newdocument.documentElement 
      ) 
      refel= None 
     elif child.nodeType!=child.DOCUMENT_TYPE_NODE: 
      newdocument.insertBefore(newdocument.importNode(child, True), refel) 
    return newdocument 
+0

grazie! Non ho bisogno di impostare doctype su documenti esistenti, solo su nuovi. – myfreeweb

+0

Uff, è una fortuna! :-) – bobince

Problemi correlati