XMLWriter class lets
us do this. You can get XMLWriter from David Megginson, the
author. Unfortunately, XMLWriter performs only minimal
well-formedness checks - in particular it doesn't ensure that open and
close tags are balanced. It wouldn't be hard to write a subclass of
XMLWriter that did that checking, though.
XMLWriter is very easy to use. An example:
import java.io.FileWriter;
import com.megginson.sax.XMLWriter;
import org.xml.sax.helpers.AttributesImpl;
public class GenerateXML
{
public static void main (String args[])
throws Exception
{
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.startDocument();
AttributesImpl attribs = new AttributesImpl();
attribs.addAttribute("","class","","","simple");
writer.startElement("","greeting","",attribs);
writer.characters("Hello, world!");
writer.endElement("greeting");
writer.endDocument();
}
}
Let's go through the example line by line:
import java.io.FileWriter; import com.megginson.sax.XMLWriter; import org.xml.sax.helpers.AttributesImpl;This just lets Java know what classes we want to use. package.
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
This creates a new XMLWriter object with output directed
to output.xml. To write to standard output, omit the
output argument. To write to a string, we could use a StringWriter.
Going back to our example, we next insert an an XML declaration:
writer.startDocument()The declaration that
writer.startDocument() emits lets us
know that the output is XML.
<?xml version="1.0" standalone="yes"?>Then we create a new attribute set and add the attribute
class =
"simple", open a <greeting> element with
those attributes and write the characters Hello, world!
and finally close the <greeting> tag. All the empty
strings are various arguments to support namespaces; normally they
should be blank. There are convenience methods that allow you to omit
these arguments if neither namespaces nor attributes are being used;
see the XMLWriter javadoc for more info.
AttributesImpl attribs = new AttributesImpl();
attribs.addAttribute("","class","","","simple");
writer.startElement("","greeting","",attribs);
writer.characters("Hello, world!");
writer.endElement("greeting");
This produces
<greeting class="simple">Hello, world!</greeting>
Then we clean up by telling writer we're done writing.
writer.endDocument();