read XML and return a NodeList - Java XML

Java examples for XML:DOM Node

Description

read XML and return a NodeList

Demo Code


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

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 {
        File xmlfile = new File("Main.java");
        String tag = "java2s.com";
        System.out.println(readXML(xmlfile, tag));
    }//from   w w  w . j  a v  a2 s.  co m

    public static NodeList readXML(File xmlfile, String tag)
            throws Exception {
        NodeList list = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlfile);
        Element rootElement = doc.getDocumentElement();
        list = rootElement.getElementsByTagName(tag);

        return list;
    }
}

Related Tutorials