Search code examples
javaxmlxom

Having Element.toXML() properly indented instead of showing the resulting string just as a single line?


The default behavior of Element.toXML() seems to be showing up the result as a single line. Is it possible to have it show the result in multiple lines, in a hierarchical way?

Example:

This is what I'd like to get

<root>
    <Fraction hash="108e898f" />
    <Integer hash="19498483" />
</root>

and this is what I'm getting at the moment:

<root><Fraction hash="108e898f" /><Integer hash="19498483" /></root>

Thanks


Solution

  • nu.xom.Serializer is exactly what you need. Here's a usage example:

    public static void main(String[] args) {
        Element root = new Element("root");  
        Element fraction = new Element("Fraction");
        fraction.addAttribute(new Attribute("hash", "108e898f"));
        root.appendChild(fraction);
        Element integer = new Element("Integer");
        integer.addAttribute(new Attribute("hash", "19498483"));
        root.appendChild(integer);
        Document doc = new Document(root);
        try {
            Serializer serializer = new Serializer(System.out, "ISO-8859-1");
            serializer.setIndent(4);
            serializer.setMaxLength(64);
            serializer.write(doc);  
        } catch (IOException ex) {
            System.err.println(ex); 
        }  
    }