Next / Previous / Contents / TCC Help System / NM Tech homepage

12. Creating a document from scratch: factory methods

Your program can create a complete document as a DOM tree. Here's a general outline for the creation of a document:

  1. Start by importing the DOM interface:

    import Ft.Xml.Domlette as domlette
    

  2. Get the DOMImplementation object:

    dom = domlette.implementation
    

  3. Create the Document instance by using the .createDocument() method of the DOMImplementation object. For the details of this method, see Section 10.1, “DOMImplementation.createDocument().

    For example, suppose you want to create an XHTML page with an html root element. This code would do it:

    doc = dom.createDocument ( None, "html", None )
    

    The Element object representing that html element will now be available in doc.documentElement.

  4. If you want to attach a document type to the document, assign the system identifier to the Document object's .systemId attribute. If there is also a public identifier, store that in the document node's .publicId.

    For example, suppose you want to declare your document's namespace as XHTML-1.0 Strict. To continue the example code above, where doc is a Document object:

    doc.publicId = "-//W3C//DTD XHTML 1.0 Strict//EN"
    doc.systemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
    

    If you don't assign a value to doc.systemId, no <!DOCTYPE ...> declaration will be generated when the document is serialized (that is, converted back to XML).

  5. Create the elements, comments, text nodes, and other parts of the document using factory methods (see Section 6, “The Document class”) on the Document object. Connect nodes together by passing each child node to the .appendChild() method on the parent node.

    To continue the above example of HTML page creation, here is the code to add a head element as a child of the html element:

    root = doc.documentElement
    head = doc.createElementNS ( None, "head" )
    root.appendChild ( head )
    

  6. Once you have assembled the tree, print it as described in Section 11, “Printing a document”.

12.1. Document.createElementNS()

To create a new Element node, you must have a Document object available.

Assuming you have a Document instance D, use this method to create a new element:

D.createElementNS(nsURI, qName)

where the arguments have these values:

nsURI

The namespace URI of the element to be created. If the element is in the default namespace, pass the value None.

qName

The qualified name of the element. This can be either a local name, or a name of the form "nsp:localName" where nsp is the namespace prefix corresponding to the nsURI.

It is your responsibility to be consistent about the association of namespace prefixes with namespace URIs.

The returned value is a new Element node with no parent. To attach a child element c to a parent element p, use:

p.appendChild(c)