Created
September 16, 2013 07:35
-
-
Save bingoohuang/6577658 to your computer and use it in GitHub Desktop.
how to let DOM4J to generate <name></name> other than <name/>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())); | |
} | |
} |
Author
bingoohuang
commented
Sep 16, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment