Famulatus

Convert XML DOM To String and String To XML DOM

Written by 
Rate this item
(0 votes)

Example for converting XML DOM to String and String to XML DOM

 

 

 

import java.io.*;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.apache.xpath.*;
import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
import org.xml.sax.*;

 

public class XMLConverter {

static Transformer transformer = null;
private final static String ENCODING = "UTF-8";


public synchronized static String DOMToString(Document doc) throws InvalidXMLException {


        // we use the same Transformer, so we must be synchronized
        StringWriter sw = new StringWriter();
        try {
            if (transformer == null) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                transformer = tFactory.newTransformer();

                transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING);

            }
            transformer.transform(new DOMSource(doc), new StreamResult(sw));


            return sw.toString();

        } catch (Exception e) {
            throw new InvalidXMLException(e);
        }
}
    
    
    

public synchronized static Document StringToDOM(String str) throws InvalidXMLException {

        // we use the same Transformer, so we must be synchronized
        StringReader sr = new StringReader(str);
        try {
            if (transformer == null) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                transformer = tFactory.newTransformer();

            }
            DOMResult dr = new DOMResult();
            transformer.transform(new StreamSource(sr), dr);

            Node n = dr.getNode();


            if (n instanceof Document) {
                return (Document) n;
            } else {
                throw new InvalidXMLException("Node is not Document");
            }

        } catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
            
            throw new InvalidXMLException(e);

        } catch (TransformerException e) {

            throw new InvalidXMLException(e);

        } catch (IllegalArgumentException e) {

            throw new InvalidXMLException(e);
        }
}

}

 

 

Read 372 times

Famulatus

More in this category: « Disk Space Info (Free space)

External links are provided for reference purposes. The Famulatus is not responsible for the content of external Internet sites. All rights reserved.

Login or Register

LOG IN

Register

User Registration
or Cancel