Convert String to an XML document. - Android XML

Android examples for XML:XML Document

Description

Convert String to an XML document.

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.Reader;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xml = "java2s.com";
        System.out.println(stringToXML(xml));
    }//  w  ww .j  a v a  2s  .  c  o m

    /**
     * Convert String to an XML document.
     */
    public static Document stringToXML(String xml) {
        try {
            return parseReader(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document parseReader(Reader reader)
            throws org.xml.sax.SAXException, IOException,
            ParserConfigurationException {
        return newDocumentBuilder().parse(
                new org.xml.sax.InputSource(reader));
    }

    private static DocumentBuilder newDocumentBuilder()
            throws ParserConfigurationException {
        // SAXParsers are not concurrency compatible, so always return a new instance to prevent thread issues 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder();
    }
}

Related Tutorials