Hello,
I am trying to use Java's XML capabilities to write a new XML file.
All of the examples that I have seen either use the DOM to import an
existing XML file, or ignore a DOM and create an XML file by simply
writing statements line by line.
My XML file is going to be pretty complex with a fair amount of
children under each node. I would like to keep track of it as a DOM,
which should make it easy to append children, then simply export it at
the end. Is there a way to do this? I still haven't been able to
simply create a new, blank document and assing it a root node. I
imagine that once I have a document with a root node, everything else
would follow pretty easily.
Thanks,
Ben
Oliver Wong - 30 Mar 2006 18:21 GMT
> Hello,
>
[quoted text clipped - 10 lines]
> imagine that once I have a document with a root node, everything else
> would follow pretty easily.
Googling for "Java DOM create blank XML" (without the quotes) gives me:
http://www.roseindia.net/xml/dom/
<abstract>
This tutorial shows you how to create blank DOM document.
[...]
In the next section I will show you how to add root and child elements to
the blank document. Saving the DOM tree to the disk file is also discussed
in the next secion.
</abstract>
- Oliver
Steve W. Jackson - 30 Mar 2006 18:58 GMT
> Hello,
>
[quoted text clipped - 13 lines]
> Thanks,
> Ben
You'll want to look more closely at the API. At its simplest, you can
use a DocumentBuilderFactory to create a DocumentBuilder, which can then
create a Document via its newDocument() method. On the Document,
createElement and then appendChild can be used to create your root
element and add it. Depending on your version of Java, you can find
multiple ways to serialize that document to a file. In 1.4.2, I've used
a TransformerFactory to get a Transformer, set its properties, and then
transform a DOMSource (your document) into a StreamResult (an output
file, with encoding specified).
I haven't used 1.5 and don't yet know what else it may offer to improve
on this, but I do know that the classes I've named here are all present
and should still work just fine.
= Steve =

Signature
Steve W. Jackson
Montgomery, Alabama