Skip to content

Instantly share code, notes, and snippets.

@bingoohuang
Created September 16, 2013 07:35
Show Gist options
  • Save bingoohuang/6577658 to your computer and use it in GitHub Desktop.
Save bingoohuang/6577658 to your computer and use it in GitHub Desktop.
how to let DOM4J to generate <name></name> other than <name/>
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.IOException;
import java.io.StringWriter;
public class Dom4jDemo {
public static Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element category = root.addElement("category");
Element id = category.addElement("id");
id.addAttribute("name", "id");
id.addText("1");
root.addElement("empty");
return document;
}
public static String xmlToString(Document document) {
try {
OutputFormat xmlFormat = new OutputFormat();
// OutputFormat.createPrettyPrint();
xmlFormat.setEncoding("UTF-8");
// If this is true, elements without any child nodes
// are output as <name></name> instead of <name/>.
xmlFormat.setExpandEmptyElements(true);
StringWriter out = new StringWriter();
XMLWriter xmlWriter = new XMLWriter(out, xmlFormat);
xmlWriter.write(document);
xmlWriter.close();
return out.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* This Demo will output:
* <?xml version="1.0" encoding="UTF-8"?>
* <root><category><id name="id">1</id></category><empty></empty></root>
*/
public static void main(String[] args) {
System.out.println(xmlToString(createDocument()));
}
}
@bingoohuang
Copy link
Author

    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment