[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: generating an DOM object from a non-XML source in Java
- From: Ronald Bourret <email@example.com>
- To: "'firstname.lastname@example.org'" <email@example.com>
- Date: Tue, 20 Mar 2001 16:46:43 -0800
"Newman, Todd" wrote:
> I've got what I hope is a simple question for the pros. I'm trying to loop
> through some delimited text and generate an XML object to end up with a
> valid XML object and/or string.
> In fact, I've done this several times before in the VB world. My steps in
> that universe look like this:
> (1) Create the DOMDocument
> (2) Load the string "<XML></XML>" into the document
I assume here that <XML> is your root element. Note that you can use any
element you want as your root -- it doesn't have to be <XML>.
> (3) Get a reference to the Document Element
> (4) Create Nodes from the DOMDocument
> (5) Append the nodes to the Document Element or one of its children
> (6) Repeat 4&5 as required
> First, I tried using com.ibm.xml.dom. With that, I am able to create an
> object of type DocumentImpl like so: (step 1)
> DocumentImpl di = new DocumentImpl();
> Then, I can get a reference to the document element: (step 3)
> ElementImpl elRoot = (ElementImpl)di.getDocumentElement();
I assume elRoot is null. You haven't created a document element yet.
> And I can create an Element: (part of step 4)
> NodeImpl node1 = (NodeImpl)di.createElement("T1");
> But I can't set the text of the element using:
This doesn't work. The nodeValue for an Element node is null by
definition. What you need to do here is create a text node, then append
the text node to node1. The whole process should look like:
// Get a new Document.
Document doc = (Document)new DocumentImpl();
// Create the root and append it to the Document
Element elRoot = doc.createElement("XML");
// Create the T1 element and append it to the root node.
Element node1 = doc.createElement("T1");
// Create a text node and append it to the T1 node.
Text t = doc.createTextNode("Todd");
Note that I used interfaces (Document, Element, etc.) as class types
instead of implementations (DocumentImpl, NodeImpl, etc.). This makes
your code independent of DOM implementation. The only part that is not
independent is creating the Document node itself -- you will either need
to isolate this code or use a factory interface, such as can be found in
Programming, Writing, and Training
XML, Databases, and Schemas