Java XML Document get elements by tag name

Description

Java XML Document 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 {/*w ww .  ja va 2  s  .  c o m*/
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("your.xml");
         NodeList children = doc.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