Java has a lot of XML packages, but it does not find a package that provides the function of the sax writer. It just needs to output the XML file in the sax mode, so I wrote one myself, containing about 100 lines of comments, it is also quite simple to use.
/*
* Created on 2005-1-29
*
* Mininal sax writer. You can use it like that:
* Xmlwriter. startdocument ();
*...
* Xmlwriter. startelement ("book ");
* Xmlwriter. addattribute ("title", "book title ");
* Xmlwriter. addattribute ("price", "$100 ");
* Xmlwriter. character ("This is a good book ");
* Xmlwriter. endelement ("book ");
*...
* Xmlwriter. enddocument ();
*/
Package com. dyz. xfe;
Import java. Io .*;
Public class xmlwriter {
Private bufferedwriter writer = NULL;
Private stringbuffer buffer = new stringbuffer ();
Private Boolean isroot = true;
Private Boolean closed = false;
Public xmlwriter (string filename)
{
Try {
Writer = new bufferedwriter (New filewriter (filename ));
} Catch (ioexception e ){
E. printstacktrace ();
}
}
Public void startdocument ()
{
Try {
Writer. Write ("<? XML version =/"1.0/"?> ");
} Catch (ioexception e ){
E. printstacktrace ();
}
}
Public void enddocument ()
{
Try {
If (buffer. Length ()> 0)
Writer. Write (buffer. tostring ());
Writer. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
Public void startelement (string ELEM)
{
If (isroot)
Isroot = false;
Else
{
If (! Closed)
Buffer. append ("> ");
}
If (buffer. Size ()> 4096)
{
Try {
Writer. Write (buffer. tostring ());
} Catch (ioexception e ){
E. printstacktrace ();
}
Buffer. Delete (0, buffer. Length ());
}
Buffer. append ("<" + ELEM );
Closed = false;
}
Public void endelement (string ELEM)
{
If (! Closed)
Buffer. append ("> ");
Buffer. append ("</" + ELEM + "> ");
Closed = true;
}
/**
* Output a XML Attribute.
* @ Param name attribute name.
* @ Param value attribute value.
*/
Public void addattribute (string name, string value)
{
Buffer. append ("" + name + "=/" "+ value + "/"");
}
/**
* Output a text node.
* @ Param Value
*/
Public void character (string value)
{
If (! Closed)
Buffer. append ("> ");
Buffer. append (value );
Closed = true;
}
}
In fact, further optimization can be done, but some simple requirements are sufficient, but JAXP is not available?