Java XML Element get elements by tag name

Description

Java XML Element get elements by tag name

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
   public static void main(String args[]) {
      try {//from  w w w .j av a  2s .co m
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("your.xml");
         Element root = doc.getDocumentElement();
         NodeList children = root.getElementsByTagName("question"); 
         for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE)
               System.out.println(node.getFirstChild().getNodeValue());
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related