No one ever believes me when I tell them how easy it is to develop programs that write XML documents. In fact, writing a program to output an XML document is unbelievably trivial. It's something an eight-year-old typing BASIC in his or her first class at computer camp can do. In Java, it's even easier than that due to Java's strong Unicode support. You don't need to know any special APIs like DOM, or SAX, or JDOM. All you need to know is how to System.out.println() . If you want to store your XML document in a file, you can use the FileOutputStream class instead. If you want to serve the document dynamically over a network, it helps to know something about servlets; but in the end, it all reduces to writing bytes onto an output stream.
In this chapter, I'm going to develop a program that writes Fibonacci numbers into an XML document. I chose this example because the Fibonacci numbers are a well-known series and are very easy to generate algorithmically so that the examples will be nicely self-contained. However, the principles of XML you learn here will be much more broadly applicable to other, more complex systems. The key idea is that data arrives from some source, is encoded in XML, and is then output. The source of the datawhether an algorithm, a file, a network socket, user input, or some other sourcereally doesn't concern us here.
I'm going to show you how to use classes you're already familiar with, such as OutputStreamWriter , String , and HTTPServlet , to generate XML documents. I am going to beat this idea into the ground until you are absolutely convinced that there is nothing special about XML documents that requires any fancy tricks to produce them. Once you've finished this chapter, you'll be thoroughly immunized against the snake-oil peddlers who want to sell you multi-hundred-thousand-dollar software to do what you can do with your existing systems for free.