XML文件示例:
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
  <VALUE>
    <NO>A1234</NO>
    <ADDR>四川省XX县XX镇XX路X段XX号</ADDR>
  </VALUE>
  <VALUE>
    <NO>B1234</NO>
    <ADDR>四川省XX市XX乡XX村XX组</ADDR>
  </VALUE>
</RESULT>
1、DOM解析
public class XMLReader {
  public static void main(String arge[]) {
    long lasting = System.currentTimeMillis();
    try {
      File f = new File("D://aa.xml");
      DocumentBuilderFactory factory = DocumentBuilderFactory
          .newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(f);
      NodeList nl = doc.getElementsByTagName("VALUE");
      for (int i = 0; i < nl.getLength(); i++) {
        System.out.print("车牌号码:"
            + doc.getElementsByTagName("NO").item(i)
                .getFirstChild().getNodeValue());

        System.out.println("车主地址:"
            + doc.getElementsByTagName("ADDR").item(i)
                .getFirstChild().getNodeValue());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
输出结果:
车牌号码:A1234车主地址:四川省XX县XX镇XX路X段XX号
车牌号码:B1234车主地址:四川省XX市XX乡XX村XX组
DOM解析关键也就是4个类的使用,分别是DocumentBuilderFactory,DocumentBuilder,Document,NodeList,就是输入Document后alt+/ 给出提示中的前三个。
//实例化工厂,调用静态方法
      DocumentBuilderFactory factory = DocumentBuilderFactory
          .newInstance();
      //创建Builder,工厂new出来
      DocumentBuilder builder = factory.newDocumentBuilder();
      //开始解析 xml文件
      Document doc = builder.parse(f);
      //通过名字 找到节点或节点集合,
      //下面就是取出需要的内容,前三布都是固定死的,不需要什么改变
      //只需要花点功夫,把需要的数据取出来即可
      //getElementsByTagName() 返回的是一个 NodeList对象
      NodeList nl = doc.getElementsByTagName("VALUE");
取数据:
要取得文本,可真是有点麻烦,不知道 getFirstChild()是什么意思

doc.getElementsByTagName("NO").item(i).getNodeName()
// 输出 NO,NO节点
doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeName());
//输出 #text 这是一个文本节点
xml中 文本是一个文本节点。 不像dom4j中是通过 element.getText()方法可以直接拿到文本的值。

取得属性:
doc.getElementsByTagName("NO").item(i).getAttributes().getNamedItem("aa")
取得