Extreme Java When vanilla Java is not enough

12Feb/090

Writing XML with namespaces using DOM

Java has a lot of ways to interact with XML files: JAXB, SAX, DOM... I don't have a favorite one: each one has its own pros and cons. SAX is great to parse adhoc, JAXB is better when you can map your XML into a POJO tree, and DOM is the choice when your XML is well-formed, but can't be easily mapped into POJO.

I'm playing with JSPX files (JSP using XML syntax), and I got an idea: "why can't I build an JSPX using DOM"? Gene Davis has a great tutorial about creating an XML using DOM. No external library needed (like JDOM). It is almost perfect, but, if I want to create a JSPX, I will use a lot of namespaces. DOM specification level 2 doesn't support namespaces directly, but you can use dirt tricks to get this. Based on Gene's example, you only need to change the root element:

Element root = doc.createElement("jsp:root");
root.setAttribute("xmlns:jsp", "http://jsp");
root.setAttribute("xmlns:f", "http://faces");
doc.appendChild(root);

The trick is to consider the namespace declarations as attributes (since this is what they are). The result XML becames:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jsp:root xmlns:jsp="http://jsp" xmlns:f="http://faces">
    <!--Just a thought-->
    <jsp:child name="value">Filler, ... I could have had a foo!</jsp:child>
</jsp:root>

BTW, I changed the child to "jsp:child" (without the xmlns attributes), removed the "OMIT_XML_DECLARATION" output property, and, to indent correctly, I added this property:

trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

Apache attribute on Sun's RI... Yikes!

Tagged as: , , No Comments