javaxmldom4j

How to make newlines between attributes in XML file by using dom4j?


I want to generate a xml file in the following format by using java : each attribute should be in separate line.

<parameters>
    <parameter 
        name="Tom" 
        city="York" 
        number="123"
    />
</parameters>

But I can only get all attributes in one line

<parameters>
    <parameter name="Tom" city="York" number="123"/>
</parameters>

I'm using dom4j, could anyone tell how I can make it? Does dom4j supports this kind of format? Thanks.


Solution

  • You cannot do it with the XMLWriter unless you want to substantially rewrite the main logic. However, since XMLWriter is also a SAX ContentHandler it can consume SAX events and serialize them to XML, and in this mode of operation, XMLWriteruses a different code path which is easier to customize. The following sub class will give you almost what you want, except that empty elements will not use the short form <element/>. Maybe that can be fixed by further tweaking.

    static class ModifiedXmlWriter extends XMLWriter {
        // indentLevel is private, need reflection to read it
        Field il;
    
        public ModifiedXmlWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException {
            super(out, format);
            try {
                il = XMLWriter.class.getDeclaredField("indentLevel");
                il.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            }
        }
    
        int getIndentLevel() {
            try {
                return il.getInt(this);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    
        @Override
        protected void writeAttributes(Attributes attributes) throws IOException {
            int l = getIndentLevel();
            setIndentLevel(l+1);
            super.writeAttributes(attributes);
            setIndentLevel(l);
        }
    
        @Override
        protected void writeAttribute(Attributes attributes, int index) throws IOException {
            writePrintln();
            indent();
            super.writeAttribute(attributes, index);
    
        }
    }
    
    public static void main(String[] args) throws Exception {
        String XML = "<parameters>\n" + 
                "    <parameter name=\"Tom\" city=\"York\" number=\"123\"/>\n" + 
                "</parameters>";
    
        Document doc = DocumentHelper.parseText(XML);
    
        XMLWriter writer = new ModifiedXmlWriter(System.out, OutputFormat.createPrettyPrint());
    
        SAXWriter sw = new SAXWriter(writer);
        sw.write(doc);
    
    }
    

    Sample output:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <parameters>
      <parameter
         name="Tom"
         city="York"
         number="123"></parameter> 
    </parameters>