XML input, output and transform utilities : Transform « XML « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » XML » Transform 




XML input, output and transform utilities
    



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public final class XMLUtils {


    private static final Map<ClassLoader, DocumentBuilderFactory> DOCUMENT_BUILDER_FACTORIES
        = Collections.synchronizedMap(new WeakHashMap<ClassLoader, DocumentBuilderFactory>());
    
    private static final Map<ClassLoader, TransformerFactory> TRANSFORMER_FACTORIES
        = Collections.synchronizedMap(new WeakHashMap<ClassLoader, TransformerFactory>());

    private XMLUtils() {
    }

    private static TransformerFactory getTransformerFactory() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = XMLUtils.class.getClassLoader();
        }
        if (loader == null) {
            return TransformerFactory.newInstance();
        }
        TransformerFactory factory = TRANSFORMER_FACTORIES.get(loader);
        if (factory == null) {
            factory = TransformerFactory.newInstance();
            TRANSFORMER_FACTORIES.put(loader, factory);
        }
        return factory;
    }
    private static DocumentBuilderFactory getDocumentBuilderFactory() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader == null) {
            loader = XMLUtils.class.getClassLoader();
        }
        if (loader == null) {
            return DocumentBuilderFactory.newInstance();
        }
        DocumentBuilderFactory factory = DOCUMENT_BUILDER_FACTORIES.get(loader);
        if (factory == null) {
            factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DOCUMENT_BUILDER_FACTORIES.put(loader, factory);
        }
        return factory;
    }
    public static Transformer newTransformer() throws TransformerConfigurationException {
        return getTransformerFactory().newTransformer();
    }

    public static DocumentBuilder getParser() throws ParserConfigurationException {
        return getDocumentBuilderFactory().newDocumentBuilder();
    }

    public static Document parse(InputSource isthrows ParserConfigurationException, SAXException,
        IOException {
        return getParser().parse(is.getSystemId());
    }

    public static Document parse(File isthrows ParserConfigurationException, SAXException,
        IOException {
        return getParser().parse(is);
    }

    public static Document parse(InputStream inthrows ParserConfigurationException, SAXException,
        IOException {
 
        return getParser().parse(in);
    }

    public static Document parse(String inthrows ParserConfigurationException, SAXException, IOException {
        return parse(in.getBytes());
    }

    public static Document parse(byte[] inthrows ParserConfigurationException, SAXException, IOException {
 
        return getParser().parse(new ByteArrayInputStream(in));
    }

    public static Document newDocument() throws ParserConfigurationException {
        return getParser().newDocument();
    }

    public static void writeTo(Node node, OutputStream os) {
        writeTo(new DOMSource(node), os);
    }
    public static void writeTo(Node node, OutputStream os, int indent) {
        writeTo(new DOMSource(node), os, indent);
    }
    public static void writeTo(Source src, OutputStream os) {
        writeTo(src, os, -1);
    }
    public static void writeTo(Source src, OutputStream os, int indent) {
        String enc = null;
        if (src instanceof DOMSource
            && ((DOMSource)src).getNode() instanceof Document) {
            enc = ((Document)((DOMSource)src).getNode()).getXmlEncoding();
        }
        writeTo(src, os, indent, enc, "no");
    }
    public static void writeTo(Source src,
                               OutputStream os,
                               int indent,
                               String charset,
                               String omitXmlDecl) {
        Transformer it;
        try {
            
            //charset = "utf-8"; 
            

            it = newTransformer();
            it.setOutputProperty(OutputKeys.METHOD, "xml");
            if (indent > -1) {
                it.setOutputProperty(OutputKeys.INDENT, "yes");
                it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                                     Integer.toString(indent));
            }
            it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
            it.setOutputProperty(OutputKeys.ENCODING, charset);
            it.transform(src, new StreamResult(os));
        catch (TransformerException e) {
            throw new RuntimeException("Failed to configure TRaX", e);
        }

    }
    public static String toString(Source sourcethrows TransformerException, IOException {
        return toString(source, null);
    }

    public static String toString(Source source, Properties propsthrows TransformerException, IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        StreamResult sr = new StreamResult(bos);
        Transformer trans = newTransformer();
        if (props == null) {
            props = new Properties();
            props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
        trans.setOutputProperties(props);
        trans.transform(source, sr);
        bos.close();
        return bos.toString();
    }

    public static String toString(Node node, int indent) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeTo(node, out, indent);
        return out.toString();
    }
    public static String toString(Node node) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeTo(node, out);
        return out.toString();
    }

    public static void printDOM(Node node) {
        printDOM("", node);
    }

    public static void printDOM(String words, Node node) {
        System.out.println(words);
        System.out.println(toString(node));
    }

    public static Attr getAttribute(Element el, String attrName) {
        return el.getAttributeNode(attrName);
    }

    public static void replaceAttribute(Element element, String attr, String value) {
        if (element.hasAttribute(attr)) {
            element.removeAttribute(attr);
        }
        element.setAttribute(attr, value);
    }




    public static QName getNamespace(Map<String, String> namespaces, String str, String defaultNamespace) {
        String prefix = null;
        String localName = null;

        StringTokenizer tokenizer = new StringTokenizer(str, ":");
        if (tokenizer.countTokens() == 2) {
            prefix = tokenizer.nextToken();
            localName = tokenizer.nextToken();
        else if (tokenizer.countTokens() == 1) {
            localName = tokenizer.nextToken();
        }

        String namespceURI = defaultNamespace;
        if (prefix != null) {
            namespceURI = (String)namespaces.get(prefix);
        }
        return new QName(namespceURI, localName);
    }


    public static Element createElementNS(Node node, QName name) {
        return createElementNS(node.getOwnerDocument(), name.getNamespaceURI(), name.getLocalPart());
    }

    public static Element createElementNS(Document root, QName name) {
        return createElementNS(root, name.getNamespaceURI(), name.getLocalPart());
    }

    public static Element createElementNS(Document root, String namespaceURI, String qualifiedName) {
        return root.createElementNS(namespaceURI, qualifiedName);
    }

    public static Text createTextNode(Document root, String data) {
        return root.createTextNode(data);
    }

    public static Text createTextNode(Node node, String data) {
        return createTextNode(node.getOwnerDocument(), data);
    }

    public static void removeContents(Node parent) {     
        Node node = parent.getFirstChild();
        while (node != null) {
            parent.removeChild(node);
            node = node.getNextSibling();
        }
    }


    public static InputStream getInputStream(Document docthrows Exception {
        DOMImplementationLS impl = null;
        DOMImplementation docImpl = doc.getImplementation();
        // Try to get the DOMImplementation from doc first before
        // defaulting to the sun implementation.
        if (docImpl != null && docImpl.hasFeature("LS""3.0")) {
            impl = (DOMImplementationLS)docImpl.getFeature("LS""3.0");
        else {
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
            if (impl == null) {
                System.setProperty(DOMImplementationRegistry.PROPERTY,
                                   "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
                registry = DOMImplementationRegistry.newInstance();
                impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
            }
        }
        LSOutput output = impl.createLSOutput();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        output.setByteStream(byteArrayOutputStream);
        LSSerializer writer = impl.createLSSerializer();
        writer.write(doc, output);
        byte[] buf = byteArrayOutputStream.toByteArray();
        return new ByteArrayInputStream(buf);
    }



    public static QName getQName(String value, Node node) {
        if (value == null) {
            return null;
        }

        int index = value.indexOf(":");

        if (index == -1) {
            return new QName(value);
        }

        String prefix = value.substring(0, index);
        String localName = value.substring(index + 1);
        String ns = node.lookupNamespaceURI(prefix);

        if (ns == null || localName == null) {
            throw new RuntimeException("Invalid QName in mapping: " + value);
        }

        return new QName(ns, localName, prefix);
    }

    public static Node  fromSource(Source srcthrows Exception {

        Transformer trans = TransformerFactory.newInstance().newTransformer();
        DOMResult res = new DOMResult();
        trans.transform(src, res);
        return res.getNode();
    }
}

   
    
    
    
  














Related examples in the same category
1.XML transformation
2.A Program That Performs XML Transformations
3.XSLT I18N
4.Use the transform.TransformerFactory plugability in the JAXP API
5.Processing XML Documents Partially
6.Set the TransformerFactory system property to generate and use translets
7.Transforming DOM Node to HTML with JAXP
8.Transformer with parameters
9.Create an XML file and attach an XSL
10.Applying XSLT Stylesheets
11.Catch TransformerException
12.Formatting an XML file using Transformer
13.Transforming an XML File with XSL into a DOM Document
14.XSL transformations: It applies a transformation to a set of employee recordsXSL transformations: It applies a transformation to a set of employee records
15.How to write an XML file. It saves a file describing a modern drawing in SVG format.
16.Applies a stylesheet to a given xml document.
17.Applies a stylesheet (that receives parameters) to a given xml document.
18.Apply some indentiation to some XML.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.