Your program can create a complete document as a DOM tree. Here's a general outline for the creation of a document:
Start by importing the DOM interface:
import Ft.Xml.Domlette as domlette
Get the DOMImplementation object:
dom = domlette.implementation
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.
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).
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 )
Once you have assembled the tree, print it as described in Section 11, “Printing a document”.
To create a new Element node,
you must have a Document object
available.
If you have a Node object
available, its .ownerDocument attribute
will point back to the Document object
that contains that node.
To create a new Document instance, see
Section 10, “The DOMImplementation object”.
Assuming you have a Document instance
, use this
method to create a new element:
D
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 " where nsp:localName" is the
namespace prefix corresponding to the nsp.
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 to a parent
element cp, use:
p.appendChild(c)