Xml Utils for dom4j : DOM « 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.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » XML » DOMScreenshots 
Xml Utils for dom4j
    
//package jomm.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.*;
import org.xml.sax.InputSource;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.util.Map;
import java.util.Hashtable;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;

/**
 @author Jorge Machado
 * @date 6/Nov/2009
 * @time 23:39:18
 * @email [email protected]
 */
public class XmlUtils {

    public static String escape(String text)
    {
        if(text == null)
            return null;
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<text.length();i++)
        {
            if (text.charAt(i== '<')
            {
                stringBuilder.append("&lt;");
            }
            else if (text.charAt(i== '>')
            {
                stringBuilder.append("&gt;");
            }
            else if (text.charAt(i== '&')
            {
                stringBuilder.append("&amp;");
            }
            else
            {
                stringBuilder.append(text.charAt(i));
            }
        }
        return stringBuilder.toString();
    }

    public static Document styleDocument(Document document,String stylesheet,boolean xslInPath, Map<String,Object> parametersthrows Exception {

        
        Transformer transformer = XmlUtils.getTransformer(stylesheet,xslInPath);
        if(parameters != null)
        {
            for(Map.Entry<String,Object> entry: parameters.entrySet())
            {
                transformer.setParameter(entry.getKey(),entry.getValue());
            }
        }
        // now lets style the given document
        DocumentSource source = new DocumentSourcedocument );
        DocumentResult result = new DocumentResult();
        transformer.transformsource, result );
        // return the transformed document
        return result.getDocument();
    }

    public static void styleDocument(Document document,String stylesheet,boolean xslInPath, Map<String,Object> parameters, OutputStream outthrows Exception {

        Transformer transformer = XmlUtils.getTransformer(stylesheet,xslInPath);
        if(parameters != null)
        {
            for(Map.Entry<String,Object> entry: parameters.entrySet())
            {
                transformer.setParameter(entry.getKey(),entry.getValue());
            }
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
        DocumentSource source = new DocumentSourcedocument );
        // now lets style the given document

            StreamResult sresult = new StreamResult(out);
            transformer.transform(source, sresult);

    }

    public static void write(Document document, Writer writerStreamthrows IOException {
        // lets write to a file
        XMLWriter writer = new XMLWriter(writerStream);
        writer.writedocument );
        writer.close();
    }

    public static void write(Document document, Writer writerStream, String encodingthrows IOException {
        // lets write to a file
        OutputFormat ou = new OutputFormat();
        ou.setEncoding(encoding);
        XMLWriter writer = new XMLWriter(writerStream,ou);
        writer.writedocument );
        writer.close();
    }


    private static TransformerFactory transFact = TransformerFactory.newInstance();
    private static Map<String, Templates> templates =new Hashtable<String,Templates>();

    private static Transformer getTransformer(String xsltFile,boolean inClassPaththrows TransformerConfigurationException, IOException
    {
        Templates tpl= XmlUtils.templates.get(xsltFile);
        if (tpl==null)
        {
            InputStream stream;
            if(inClassPath)
                stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsltFile);
            else
                stream = new FileInputStream(xsltFile);
            Source xsltSource = new StreamSource(stream);
            tpl = XmlUtils.transFact.newTemplates(xsltSource);
            XmlUtils.templates.put(xsltFile,tpl);
        }
        return tpl.newTransformer();

    }


    public static Document parse(InputSource sourcethrows DocumentException, MalformedURLException {
        SAXReader reader = new SAXReader();
        XmlUtils.createIgnoreErrorHandler(reader);
        return reader.read(source);
    }

    public static Document parse(InputStream stream, String encodingthrows DocumentException, MalformedURLException {
        InputSource inputSource = new InputSource(stream);
        inputSource.setEncoding(encoding);
        SAXReader reader = new SAXReader();
        XmlUtils.createIgnoreErrorHandler(reader);
        return reader.read(inputSource);
    }

    public static Document parse(InputStream streamthrows DocumentException, MalformedURLException {
        InputSource inputSource = new InputSource(stream);
        SAXReader reader = new SAXReader();
        XmlUtils.createIgnoreErrorHandler(reader);
        return reader.read(inputSource);
    }

    public static void writeSout(Document documentthrows IOException
    {
        // Compact format to System.out
        OutputFormat format = OutputFormat.createCompactFormat();
        XMLWriter writer = new XMLWriterSystem.out, format );
        writer.writedocument );
    }

    public static Document parse(String xmlthrows DocumentException
    {
        SAXReader reader = new SAXReader();
        XmlUtils.createIgnoreErrorHandler(reader);
        return reader.read(new StringReader(xml));
    }

    public static Document parse(URL urlthrows DocumentException, IOException {
        URLConnection urlConnection;
        DataInputStream inStream;
        urlConnection = url.openConnection();
        ((HttpURLConnectionurlConnection).setRequestMethod("GET");

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(false);
        urlConnection.setUseCaches(false);
        inStream = new DataInputStream(urlConnection.getInputStream());

        byte[] bytes = new byte[1024];
        int read;
        StringBuilder builder = new StringBuilder();
        while((read = inStream.read(bytes)) >= 0)
        {
            String readed = new String(bytes,0,read,"UTF-8");
            builder.append(readed);
        }
        SAXReader reader = new SAXReader();


        XmlUtils.createIgnoreErrorHandler(reader);
//        InputSource inputSource = new InputSource(new InputStreamReader(inStream, "UTF-8"));
//        inputSource.setEncoding("UTF-8");
        Document dom = reader.read(new StringReader(builder.toString()));
        inStream.close();
//        new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("retrieval.xml"), "UTF-8")
        return dom;
    }

    public static void createIgnoreErrorHandler(SAXReader reader)
    {
        reader.setValidation(false);
        reader.setErrorHandler(new ErrorHandler()
        {

            public void warning(SAXParseException exceptionthrows SAXException {
                //System.out.println(exception);
            }

            public void error(SAXParseException exceptionthrows SAXException
            {
                //System.out.println(exception);
            }

            public void fatalError(SAXParseException exceptionthrows SAXException
            {
                //System.out.println(exception);
            }
        });
    }


    public static void write(Document document,OutputStream streamthrows IOException
    {
        // lets write to a file
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
//        OutputFormat.createPrettyPrint()
        outputFormat.setIndent(true);
        outputFormat.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(stream,outputFormat);
        writer.writedocument );
        writer.close();
    }



}

   
    
    
    
  
Related examples in the same category
1.Parsing a Document Using JAXP
2.XML Document information by DOM
3.Using DOM for Syntax Checking
4.Using the DOM Parser to Build a Document TreeUsing the DOM Parser to Build a Document Tree
5.DOM FeaturesDOM Features
6.DOM level 2 EventsDOM level 2 Events
7.Searching through a document
8.Check a vendor's DOM implementationCheck a vendor's DOM implementation
9.Make up and write an XML document, using DOMMake up and write an XML document, using DOM
10.Creating XML Document using DOM
11.Loading an XML Document using DOM
12.Parse an XML string: Using DOM and a StringReader.
13.Create an XML document with DOM
14.Extracting an XML formatted string out of a DOM object
15.Reading an XML Document and create user-defined object from DOM
16.Visiting All the Nodes in a DOM Document
17.Generating SAX Parsing Events by Traversing a DOM Document
18.Converting an XML Fragment into a DOM Fragment
19.A utility class which provides methods for working with a W3C DOM
20.XML DOM Utilities
21.Convenience methods for working with the DOM API
22.DOM Utils
23.Utilities to read DOM
24.W3C DOM utility methods
25.Read XML as DOM
26.Utility method for parsing the XML with DOM
27.Handles DOM processing allowing the reading and writing of hierarchical structures as XML files.
28.DocWriter has a static method for writing XML documents with a writer
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.