Parse XML File and get element by name - Android XML

Android examples for XML:XML Element

Description

Parse XML File and get element by name

Demo Code


//package com.java2s;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] argv) throws Exception {
        String in_TagName = "java2s.com";
        String in_FileName = "java2s.com";
        System.out.println(ParaseXMLFile(in_TagName, in_FileName));
    }// w  w  w .j a  v a2s. c o m

    public static Element ParaseXMLFile(String in_TagName,
            String in_FileName) throws Exception {
        // System.out.println(in_FileName);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(in_FileName);
        Element root = doc.getDocumentElement();
        NodeList fields = root.getElementsByTagName(in_TagName);
        if (fields.getLength() != 1) {
            throw new Exception(in_TagName);
        }
        return (Element) fields.item(0);

    }
}

Related Tutorials