Skip to content

Instantly share code, notes, and snippets.

@adrobisch
Created August 25, 2015 14:25
Show Gist options
  • Save adrobisch/290b10c56d433e7f590c to your computer and use it in GitHub Desktop.
Save adrobisch/290b10c56d433e7f590c to your computer and use it in GitHub Desktop.
XML Builder for Java 8
/**
Usage
=====
XmlBuilder xml = new XmlBuilder(outputStream);
xml.start()
.tag("version", versionTag -> versionTag.content(pojo.getVersion()))
.tag("time", timeTag -> timeTag.content(pojo.getTime()))
.tag("data", dataTag -> {
pojo.getItems().forEach(item -> dataTag.child("item", itemTag -> itemTag.attribute("id", pojo.getId())));
}).end();
*/
public class XmlBuilder {
final XMLOutputFactory factory = createFactory();
final OutputStream outputStream;
final XMLStreamWriter writer;
public XmlBuilder(OutputStream outputStream) {
this.outputStream = outputStream;
this.writer = createWriter(outputStream);
}
protected XMLStreamWriter createWriter(OutputStream outputStream) {
try {
return factory.createXMLStreamWriter(outputStream);
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
protected XMLOutputFactory createFactory() {
return XMLOutputFactory.newInstance();
}
public XmlBuilder start() {
try {
writer.writeStartDocument();
return this;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public XmlBuilder end() {
try {
writer.writeEndDocument();
writer.flush();
writer.close();
return this;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public XmlBuilder tag(String name, TagFunction scopeFunction) {
try {
writer.writeStartElement(name);
scopeFunction.apply(new TagContext(name, this));
writer.writeEndElement();
return this;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public interface TagFunction {
void apply(TagContext tagContext);
}
public class TagContext {
String name;
private XmlBuilder xmlBuilder;
public TagContext(String name, XmlBuilder xmlBuilder) {
this.name = name;
this.xmlBuilder = xmlBuilder;
}
public String getName() {
return name;
}
public TagContext attribute(String name, String value) {
try {
writer.writeAttribute(name, value);
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return this;
}
public TagContext content(Object content) {
try {
writer.writeCharacters(content.toString());
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return this;
}
public XmlBuilder child(String name, TagFunction scopeFunction) {
return xmlBuilder.tag(name, scopeFunction);
}
public TagContext child(String name) {
try {
writer.writeEmptyElement(name);
return this;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public TagContext cdata(Object content) {
try {
writer.writeCData(content.toString());
return this;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment