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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值