Android XML Element Create getRoot(String xml, String charset)

Here you can find the source of getRoot(String xml, String charset)

Description

get Root

Declaration

public static Element getRoot(String xml, String charset) 

Method Source Code

//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.xml.sax.SAXException;
import android.util.Log;

public class Main {
    private static final String TAG = "XMLUtils";

    public static Element getRoot(String xml, String charset) {
        InputStream in = null;// w w  w  . j ava  2 s  . c  om
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();

        byte[] bytes;
        try {
            bytes = xml.getBytes(charset);
            in = new ByteArrayInputStream(bytes);

            DocumentBuilder documentBuilder = builderFactory
                    .newDocumentBuilder();
            Document dom = documentBuilder.parse(in);
            Element root = dom.getDocumentElement();

            if (root == null) {
                throw new RuntimeException("Invalid XML");
            }
            return root;
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (ParserConfigurationException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (SAXException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return null;
    }
}

Related

  1. getRoot(String xml, String charset)
  2. getRoot(String xml, String charset)