Java XML Element get attribute

Description

Java XML Element get attribute

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

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

public class Main {
   public static void main(String args[]) {
      try {/*from w  w  w.j a v a2 s  .  com*/
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("questions.xml");
         Element e = doc.getElementById("q1");
         String value = e.getAttribute("id");
         System.out.print(value + ". "); 
         System.out.println(e.getFirstChild().getNodeValue()); 
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Get attribute from elements

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 .  c  o  m
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         DocumentBuilder parser = factory.newDocumentBuilder();
         Document doc = parser.parse("your.xml");
         Element root = doc.getDocumentElement();
         NodeList children = root.getElementsByTagName("data");
         for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            String value = ((Element) node).getAttribute("no");
            System.out.print(value + ". "); 
            System.out.println(node.getFirstChild().getNodeValue());
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related