当前位置: 移动技术网 > IT编程>开发语言>Java > Java如何基于DOM解析xml文件

Java如何基于DOM解析xml文件

2020年09月17日  | 移动技术网IT编程  | 我要评论
一、java解析xml、解析xml四种方法、dom、sax、jdom、dom4j、xpath此文针对其中的dom方法具体展开介绍及代码分析sax、dom是两种对xml文档进行解析的方法(没有具体实现,

一、java解析xml、解析xml四种方法、dom、sax、jdom、dom4j、xpath

此文针对其中的dom方法具体展开介绍及代码分析

sax、dom是两种对xml文档进行解析的方法(没有具体实现,只是接口),所以只有它们是无法解析xml文档的;jaxp只是api,它进一步封装了sax、dom两种接口,并且提供了domcumentbuilderfactory/domcumentbuilder和saxparserfactory/saxparser(默认使用xerces解释器)。如果是嵌入式的情况下建议使用sax方法进行解析,因为它不需要一下子把数据都保存到内存中然后再解析是可以逐步解析的。而dom不行,必须一次性把数据存到内存中,然后一并解析。这样做虽然速度会很快,但是同时也加大了对内存的消耗。如果文件很大的情况下不建议dom解析。

二、【dom 简单使用介绍】

1、【dom(document object model) 】

由w3c提供的接口,它将整个xml文档读入内存,构建一个dom树来对各个节点(node)进行操作。

下面一段是dom解析xml的一个案例一起来看一下。

【xml原文件】

<?xml version = "1.0" encoding = "utf-8"?>
<staffs>
  <staff id="1">
    <name>tom_zhang1</name>
    <age>19</age>
    <sex>男</sex>
    <phone>18677435526</phone>
    <group>
      <id>1</id>
      <name>technical department</name>
    </group>
  </staff>
  <staff id="2">
    <name>susy_wang</name>
    <age>18</age>
    <sex>女</sex>
    <phone>18962459987</phone>
    <group>
      <id>2</id>
      <name>financial department</name>
    </group>
  </staff>
 
  <staff id="3">
    <name>jack_ma</name>
    <age>45</age>
    <sex>男</sex>
    <phone>1867755334</phone>
    <group>
      <id>3</id>
      <name>financial department</name>
    </group>
  </staff>
</staffs>

【代码】

staff 类

package entity;

public class staff {
  
  private int id;
  private string name;
  private int age;
  private string sex;
  private string phone;
  private stugroup group;
  public int getid() {
    return id;
  }
  public void setid(int id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  public string getsex() {
    return sex;
  }
  public void setsex(string sex) {
    this.sex = sex;
  }
  public string getphone() {
    return phone;
  }
  public void setphone(string phone) {
    this.phone = phone;
  }
  public stugroup getgroup() {
    return group;
  }
  public void setgroup(stugroup group) {
    this.group = group;
  }
  public staff() {
    super();
    // todo auto-generated constructor stub
  }
  public staff(int id, string name, int age, string sex, string phone,
      stugroup group) {
    super();
    this.id = id;
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.phone = phone;
    this.group = group;
  }
  @override
  public string tostring() {
    return "staff [age=" + age + ", group=" + group + ", id=" + id
        + ", name=" + name + ", phone=" + phone + ", sex=" + sex + "]";
  }
}

group 类

package entity;

public class group {
  
  private int id;
  private string name;
  public int getid() {
    return id;
  }
  public void setid(int id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public group() {
    super();
    // todo auto-generated constructor stub
  }
  public group(int id, string name) {
    super();
    this.id = id;
    this.name = name;
  }
  @override
  public string tostring() {
    return "group [id=" + id + ", name=" + name + "]";
  } 
}

注释: staff类不需解释,xml文件中有几个<>就需要创建几个字段。group类的创建是因为group本身又是一个节点,它有它自己的字段。因此在这边把这种情况单独作为一个类创建,同时也方便日后维护管理。依次类推如果有更多的子类,方法一样创建相应的类即可。

无论是dom解析还是sax解析,都是通过一个叫做parser的解释器,来对xml文件进行解析。而这个解析器是需要我们手动创建的,接下来就一起来看一下解释器中的代码,也是最主要的代码。

dom_parser(解析器)

package parser;

import java.io.file;
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;

import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;

import org.w3c.dom.document;
import org.w3c.dom.element;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
import org.xml.sax.saxexception;

import entity.stugroup;
import entity.staff;

public class dom_parser {

  public static list<staff> parser(string filename) {

    list<staff> staffs = new arraylist<staff>(); //创建一个arraylist来装数据

    documentbuilderfactory factory = null;  //documentbuilderfactory,documentbuilder,document分别是dom解析的工厂类
    documentbuilder builder = null;
    document doc = null;
    staff staff = null;           //方便日后实例化
    stugroup group = null;         //同上

    try {
      factory = documentbuilderfactory.newinstance();  //工厂类实例化
      builder = factory.newdocumentbuilder();      //工厂类实例化
      doc = builder.parse(new file(filename));     //通过.parser方法加载文件

      element root = doc.getdocumentelement();     //element方法中的.getdocumentelement()代表获取xml文件的头文件内容

      nodelist nodelist = root.getelementsbytagname("staff"); //获取tagname,每一个<>中的字段为一个tagname.作为一个nodelist来保存
            //循环这个nodelist,然后得到每个nodelist中的item。根据获取到的值的索引最终通过.set方法得到这个值
      for (int index = 0; index < nodelist.getlength(); index++) {
        staff = new staff();
        node node = nodelist.item(index);
        staff.setid(integer.parseint(node.getattributes().getnameditem(
            "id").gettextcontent()));
        // system.out.println(staff);

        nodelist childnode = node.getchildnodes();  //设置一个childnode为了存放nodelist下子<>中的tagname
                  //同上循环子childnode这个list,获取到每个元素的下标。再通过.set方法分别得到每个元素的值。
        for (int i = 0; i < childnode.getlength(); i++) {
          node childitem = childnode.item(i);
          if (childitem.getnodename().equals("name")) {
            staff.setname(childitem.gettextcontent());
          } else if (childitem.getnodename().equals("age")) {
            staff.setage(integer.parseint(childitem
                .gettextcontent()));
          } else if (childitem.getnodename().equals("sex")) {
            staff.setsex(childitem.gettextcontent());
          } else if (childitem.getnodename().equals("phone")) {
            staff.setphone(childitem.gettextcontent());
          } else if (childitem.getnodename().equals("group")) {
            nodelist groupnode = childitem.getchildnodes();

            for (int j = 0; j < groupnode.getlength(); j++) {
              node groupitem = groupnode.item(j);
                            
              if (groupitem.getnodename().equals("id")) {
                group = new stugroup(); //这里的实例化很重要,切记不要实例化错误地方
                string groupid = groupitem.gettextcontent();
                group.setid(integer.parseint(groupid));
                staff.setgroup(group);
              } else if (groupitem.getnodename().equals("name")) {
                string groupname = groupitem.gettextcontent();
                group.setname(groupname);
                staff.setgroup(group);
              }
            }

          }

        }
        staffs.add(staff); //最终我们要把staff这个对象追加到staffs这个集合中。
      }

    } catch (parserconfigurationexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    } catch (saxexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    } catch (ioexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
    }
    return staffs; //返回这个集合
  }
}

【测试类】

package parser;
 
import java.util.list;
 
import entity.staff;
 
public class test {
   
  public static void main(string[] args) {
     
    string file = "c:/users/ibm_admin/desktop/xml/staff.xml";  //指定文件地址
    list<staff> staffs = dom_parser.parser(file);  //因为我们创建的解析器的名字叫dom_parser所以在这里调用dom_parser.parser()方法。()中参数为文件地址。        //循环并打印结果
    for(staff list:staffs){
      system.out.println(list);
    }
  }
}

【打印结果】

打印结果如下。可以看到xml中每个tagename以及对应的值,通过dom解析的方式把结果都一一的被获取并打印出来了。

目前我们是把数据放到了arraylist内存中。后续可以把数据存放到数据库中。

staff [age=19, group=group [id=1, name=technical department], id=1, name=tom_zhang1, phone=18677435526, sex=男]
staff [age=18, group=group [id=2, name=financial department], id=2, name=susy_wang, phone=18962459987, sex=女]
staff [age=45, group=group [id=3, name=financial department], id=3, name=jack_ma, phone=1867755334, sex=男]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网