Java XML Node Serialize serialize(Node n, StreamResult sr)

Here you can find the source of serialize(Node n, StreamResult sr)

Description

serialize

License

Apache License

Declaration

public static void serialize(Node n, StreamResult sr) throws IOException, TransformerException 

Method Source Code

//package com.java2s;
/*//from  w  w  w . j a  v a  2 s. c o  m
 * Copyright 2012 Johns Hopkins University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    private static SAXTransformerFactory transformerFactory;

    public static void serialize(Node n, StreamResult sr) throws IOException, TransformerException {
        TransformerHandler hd = newTransformerHandler();
        Transformer serializer = hd.getTransformer();

        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(n);
        serializer.transform(source, sr);
    }

    public static TransformerHandler newTransformerHandler() throws TransformerConfigurationException {
        if (transformerFactory == null) {
            transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        }

        return transformerFactory.newTransformerHandler();
    }
}

Related

  1. getSerializer(final File file)
  2. serialise(Node node)
  3. serialiseBytes(Node n)
  4. serialize(Element e, boolean omitXMLDeclaration)
  5. serialize(Node doc)
  6. serialize(Node node)
  7. serialize(Node node)
  8. serialize(Node node, File outdir, String fileName)
  9. serialize(NodeList nodeList)