get Root Element from XML String - Android XML

Android examples for XML:XML Document

Description

get Root Element from XML String

Demo Code


//package com.java2s;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

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

public class Main {
    public static Element getRoot(String xml, String charset) {
        try {//from   w w  w .  j  a v a 2 s. c om
            InputStream in = null;
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            factory.setValidating(false);
            byte[] bytes = xml.getBytes(charset);
            in = new ByteArrayInputStream(bytes);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(in);
            Element root = dom.getDocumentElement();
            if (root == null) {
                throw new RuntimeException("XML invalido");
            }
            return root;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

Related Tutorials