Java XML Document Clone deepCopyDocument(Document ttml, File target)

Here you can find the source of deepCopyDocument(Document ttml, File target)

Description

deep Copy Document

License

Apache License

Declaration

public static void deepCopyDocument(Document ttml, File target)
            throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

public class Main {
    public static void deepCopyDocument(Document ttml, File target)
            throws IOException {
        try {//from  w w  w.java 2 s .  com
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//*/@backgroundImage");
            NodeList nl = (NodeList) expr.evaluate(ttml,
                    XPathConstants.NODESET);
            for (int i = 0; i < nl.getLength(); i++) {
                Node backgroundImage = nl.item(i);
                URI backgroundImageUri = URI.create(backgroundImage
                        .getNodeValue());
                if (!backgroundImageUri.isAbsolute()) {
                    copyLarge(
                            new URI(ttml.getDocumentURI())
                                    .resolve(backgroundImageUri).toURL()
                                    .openStream(), new File(target.toURI()
                                    .resolve(backgroundImageUri).toURL()
                                    .getFile()));
                }
            }
            copyLarge(new URI(ttml.getDocumentURI()).toURL().openStream(),
                    target);

        } catch (XPathExpressionException e) {
            throw new IOException(e);
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }

    private static long copyLarge(InputStream input, File outputFile)
            throws IOException {
        byte[] buffer = new byte[16384];
        long count = 0;
        int n = 0;
        outputFile.getParentFile().mkdirs();
        FileOutputStream output = new FileOutputStream(outputFile);
        try {
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
                count += n;
            }
        } finally {
            output.close();
        }
        return count;
    }
}

Related

  1. copyDomDocument(Document originalDomDoc)
  2. copyElement(Element orig, Document newOwner, Set blankTextNodes)
  3. copyNode(Document new_doc, Node node)
  4. copyNode(final Document newDoc, final Node node)
  5. deepCloneDocument(Document doc, DOMImplementation impl)