Java HTML / XML How to - Get DOM xml attributes








Question

We would like to know how to get DOM xml attributes.

Answer

import java.io.File;
//from  w w w .  ja  va2  s .co  m
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[] args) throws Exception {
    File CFile = new File("data.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(CFile);

    NodeList pizzas = document.getElementsByTagName("Pizza");

    for (int i = 0; i < pizzas.getLength(); i++) {
      Element pizzaSize = (Element) pizzas.item(i);
      String pSize = pizzaSize.getAttribute("Size");

      if (pSize.equalsIgnoreCase("Large"))
        System.out.println(10.0);
      if (pSize.equalsIgnoreCase("Medium"))
        System.out.println(7.0);
      if (pSize.equalsIgnoreCase("Small"))
        System.out.println(5.0);
    }
  }
}