SimpleXMLDoc revisited
It is 2020, JSON is supposed to have won, with a challenger in sight. XML with its fine distinction between Elements, Attributes and clear ownership demarked by name spaces, was supposed to be gone. But OData made it necessary to look again, as did CalDAV
Out into the OutputStream
The initial version was introduced in the context of XAgents which mandated an OutputStream. I find that adequate and useful, so I kept that. If you just want a String, a ByteArrayOutputStream will do quite nicely
Fluent methods
The big change to the revamped version is the addition of a fluent API. Each method call returns the object instance itself, so you can chain your document creation to look modern (and type less)
Namespace and attributes
Originally I though "simple" would be sufficient to create Elements
only. But as time goes by one starts to appreciate name spaces and Attributes
, so I added support for these too. To keep things simple: once we specify the namespace at the beginning of the document, we can simply refer to it by its alias name.
A sample:
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final SimpleXMLDoc doc = new SimpleXMLDoc(out);
doc.addNamespace("X", "https://xmen.org")
.addNamespace("", "https://whyOhWhy.com/xml")
.setXmlStyleSheet("somestle.xslt")
.openElement("Endpoints")
.openElement(doc.element("X:Endpoint")
.addAttribute("name", "A Name")
.addAttribute("url", "http://anywhere/")
.addAttribute("meta", "meta not metta"))
.closeElement(1)
.addSimpleElement("description", "Something useful")
.closeDocument();
System.out.println(out.toString());
Key methods
addNamespace
: adds one name space and establishes the alias. To keep it simple, namespaces are defined only at the beginning fo the documentsetXmlStyleSheet
: Same here, needs to be defined at the beginning - after all this class streams the result and stylesheets only start at the beginningOpenElement
starts a new XML Element. When provided with a string, it is an attribute free element, that can include the namespace abbreviation. When using a doc.element, we can add attributesaddSimpleElement
: add an element, its String content and close itcloseElement
: write out a number of closing tags. It deliberately uses number of tags and not tag names, so you don't need to track the names you have opened. Ensures that XML stays validcloseDocument
: closes all remaining Elements in the correct sequence and closes the document. Can be called once only
Check the full source code for details
As usual YMMV
Posted by Stephan H Wissel on 13 April 2020 | Comments (0) | categories: Java XML