Introduction

WriteXml is a library for writing well formed XML written in Java. It's intended to make it easy to produce XML, and as a foundation for domain specific languages for your XML documents. It is open source, and free for you to use.

The latest version of WriteXml available for download is 1.3. The javadoc is also available online.

Example

A brief example demonstrates the generation the Maven dependency snippet for including WriteXml in a Maven project:

import net.sourceforge.writexml.*; import java.io.StringWriter; import java.net.URI; import static net.sourceforge.writexml.Attributes.attributes; import static net.sourceforge.writexml.Namespace.namespace; import static net.sourceforge.writexml.Tag.tag; import static net.sourceforge.writexml.TagName.tagName; import static net.sourceforge.writexml.Text.text; ... static final XmlFormatter FORMATTER = new PrettyXmlFormatter(); private static Tag pomTag(String name, TagContent... children) { return tag( namespace(URI.create("http://maven.apache.org/POM/4.0.0")), tagName(name), attributes(), children ); } public static String deps(String version) throws XmlWriteException { final Tag rootTag = pomTag("dependency", pomTag("groupId", text("net.sourceforge.writexml")), pomTag("artifactId", text("writexml")), pomTag("version", text(version)) ); StringWriter stringWriter = new StringWriter(); FORMATTER.write(rootTag, stringWriter); return stringWriter.toString(); }

In essence, we are instantiating a root Tag, and using a CompactXmlFormatter to output it to a Writer. Notice the beginnings of a domain specific language emerging: We have defined a pomTag method, which generates a tag in the correct namespace, with no attributes - a shorthand for the kind of tag we use in a POM.

Calling deps("1.3") will return the following String:

<?xml version="1.0" encoding="UTF-8"?><dependency xmlns="http://maven.apache.org/POM/4.0.0"> <groupId>net.sourceforge.writexml</groupId> <artifactId>writexml</artifactId> <version>1.3</version> </dependency>

If we had used reserved XML characters, like '<' or '>', WriteXml would have escaped them appropriately.