DOM Parse XML - Android XML

Android examples for XML:XML Parse

Description

DOM Parse XML

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import android.text.TextUtils;

public class Main {
    /**//from  w ww . j  av a 2  s . c  om
     * DOM?XML
     */
    public static Document parseXML(InputStream inStream) {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(inStream);
            return dom;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * DOM?XML
     */
    public static Document parseXML(File file) {
        if (file == null || !file.exists())
            return null;
        Document dom = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            dom = parseXML(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return dom;
    }

    /**
     * DOM?XML
     */
    public static Document parseXML(String path) {
        if (TextUtils.isEmpty(path))
            return null;
        Document dom = parseXML(new File(path));
        return dom;
    }
}

Related Tutorials