Serializing XML DOMs using Xerces/Xalan

前端之家收集整理的这篇文章主要介绍了Serializing XML DOMs using Xerces/Xalan前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的XML相关文章