DOM解析

XML解析一:DOM解析
1.创建一个工厂,注:不用NEW对象,直接调方法
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
List<Student> allStus = null;
2.创建DOM解析器
DocumentBuilder db =dbf.newDocumentBuilder();
3.XML文件加载进解析器DocumentBuilder
File myfile = new File("此处放入XML文件路劲");
if (myfile.exists()) {
FileInputStream fis=new FileInputStream(myfile);
Document dom = db.parse(fis);
4.从XML中提取数据
           NodeList students = dom.getElementsByTagName("student");
System.out.println("多少个节点:"+students.getLength());
allStus = new ArrayList<Student>();
//循环遍历每一个节点获取其中存储的数据
           for (int i = 0; i < students.getLength(); i++) {
     Element studentNode = (Element) students.item(i);
              //取得XML文件中保存的学生编号
      String stuId = studentNode.getAttribute("id");
     //<student><name>
     NodeList names = studentNode.getElementsByTagName("name");
              Element nameNode = (Element) names.item(0);
    //<name>张三
    Text nameText = (Text) nameNode.getFirstChild();
    //获取以文本形式保存的学生姓名
    String studentName = nameText.getNodeValue();


第二种方法:
           NodeList ages =dom.getElementsByTagName("age");
Element ageNode = (Element) ages.item(i);

          Text ageText = (Text) ageNode.getFirstChild();

         String studentAge = ageText.getNodeValue();
         Student stu = new Student(Integer.parseInt(stuId), studentName, Integer.parseInt(studentAge));
allStus.add(stu);
}
          } else {
System.out.println("文件不存在");
}
          for (Student stu : allStus) {
System.out.println("学生姓名"+stu.getStuName());
}}
最后抛个异常搞定

你可能感兴趣的:(dom解析)