copyright 2004 by Terrance Gene Davis (http://genedavissoftware.com/)
A Simple XML Document
Unfortunately DOM XML documents in Java have a reputation for being
hard to create. This simply isn’t true. The construction process is
very wordy though, but if you have a cheat sheet (like this tutorial),
then they really aren’t so bad.
I’m going to show you a base example that does everything that most
documents need to do. It has a root element. The root contains
another element that is its child. The root contains a comment too.
The child element has a name-value attribute. The child also contains
some arbitrary text.
If you have ever written a simple web page you will find this very
similar in format. XML documents are very human friendly. Here is
the simple XML Document we’ll create. You can base extremely complex
documents off of this base example.
Now I do make the assumption that you know what XML is. You create your own
mark-up language using the rules of XML. XML is not the tags, but the format
of the tags. If that makes no sense, start with a tutorial that explains
what XML is. XML is really quite fun when you get use to it.
Parts of the Java DOM Document
Now as I said earlier, there are several classes used when handling XML and
they are spread across several packages. I wouldn’t bother memorizing them.
They will commit themselves to memory if you spend a significant amount of
time using them. If you only use them once in a while, just remember where
to find a good tutorial to review when you need to.
Now before you start looking at the code, you should realize that only three
tasks occur in it. First you need a DOM document to put your XML into. Second,
the XML is assembled in tree fashion with the root element at the top. The
root is added to the Document object. Other elements can be added to the root,
and attributes are added to any elements. Comments and Text may be added to
any of the elements. Third you need to transform your XML tree into something
like an OutputStream or Writer.
So here is the code. You can pretty much tell what is going on. Just look
at the comments if something isn’t clear.