import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
//Serialization classes
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;public class XMLUtils {
/** Test document, not pretty-print formatted */
public static final String TEST_DOC = "<MyDoc \n\n\n"
+ "name=\"test\">\n\n\n"
+ "<Ninja><Monkey>1</Monkey><Monkey>2</Monkey>\n"
+ "</Ninja></MyDoc>";public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(TEST_DOC.getBytes()));
// File output = File.createTempFile("SerializeTest", ".xml");
File output = new File("D:\\SerializeTest.xml");
FileOutputStream out = new FileOutputStream(output);
OutputFormat outputFormat = new OutputFormat();outputFormat.setOmitComments(false);
outputFormat.setIndenting(true);
outputFormat.setIndent(4);
outputFormat.setPreserveSpace(false);XMLSerializer serializer = new XMLSerializer(outputFormat);
serializer.setOutputByteStream(out);
serializer.serialize(doc);
out.close();
System.out.println("Output is pretty printed at: "
+ output.getCanonicalPath());
}}
说明:import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;来自:xercesImpl.jar
文章来源: http://stackoverflow.org/wiki/Serializing_XML_DOMs_using_Xerces/Xalan
Serializing XML DOMs using Xerces/Xalan
最新推荐文章于 2020-03-27 21:28:48 发布