zoukankan      html  css  js  c++  java
  • Java Dom解析xml

    Dom解析是将xml文件全部载入,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件,下面结合这个xml文件来进行dom解析。

    Xml代码 
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <books>  
    3.     <book id="12">  
    4.         <name>thinking in java</name>  
    5.         <price>85.5</price>  
    6.     </book>  
    7.     <book id="15">  
    8.         <name>Spring in Action</name>  
    9.         <price>39.0</price>  
    10.     </book>  
    11. </books>  

     然后结合一张图来发现dom解析时需要注意的地方



     

    在这里当我们得到节点book时,也就是图中1所画的地方,如果我们调用它的getChildNodes()方法,大家猜猜它的子节点有几个?不包 括它的孙子节点,thinking in java这种的除外,因为它是孙子节点。它总共有5个子节点,分别是图中2、3、4、5、6所示的那样。所以在解析时,一定要小心,不要忽略空白的地方。

    然后看代码来解析book.xml文件

    DomParseService.java

    Java代码 
    1. import java.io.InputStream;  
    2. import java.util.ArrayList;  
    3. import java.util.List;  
    4.   
    5. import javax.xml.parsers.DocumentBuilder;  
    6. import javax.xml.parsers.DocumentBuilderFactory;  
    7.   
    8. import org.w3c.dom.Document;  
    9. import org.w3c.dom.Element;  
    10. import org.w3c.dom.NodeList;  
    11. import org.w3c.dom.Node;  
    12.   
    13. import com.xtlh.cn.entity.Book;  
    14.   
    15. public class DomParseService {  
    16.     public List<Book> getBooks(InputStream inputStream) throws Exception{  
    17.         List<Book> list = new ArrayList<Book>();  
    18.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
    19.         DocumentBuilder builder = factory.newDocumentBuilder();  
    20.         Document document = builder.parse(inputStream);  
    21.         Element element = document.getDocumentElement();  
    22.           
    23.         NodeList bookNodes = element.getElementsByTagName("book");  
    24.         for(int i=0;i<bookNodes.getLength();i++){  
    25.             Element bookElement = (Element) bookNodes.item(i);  
    26.             Book book = new Book();  
    27.             book.setId(Integer.parseInt(bookElement.getAttribute("id")));  
    28.             NodeList childNodes = bookElement.getChildNodes();  
    29. //          System.out.println("*****"+childNodes.getLength());  
    30.             for(int j=0;j<childNodes.getLength();j++){  
    31.                 if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE){  
    32.                     if("name".equals(childNodes.item(j).getNodeName())){  
    33.                         book.setName(childNodes.item(j).getFirstChild().getNodeValue());  
    34.                     }else if("price".equals(childNodes.item(j).getNodeName())){  
    35.                         book.setPrice(Float.parseFloat(childNodes.item(j).getFirstChild().getNodeValue()));  
    36.                     }  
    37.                 }  
    38.             }//end for j  
    39.             list.add(book);  
    40.         }//end for i  
    41.         return list;  
    42.     }  
    43. }  

     Book.java用来组装数据和盛放数据

    Java代码  
    1. public class Book {  
    2.     private int id;  
    3.     private String name;  
    4.     private float price;  
    5.     public int getId() {  
    6.         return id;  
    7.     }  
    8.     public void setId(int id) {  
    9.         this.id = id;  
    10.     }  
    11.     public String getName() {  
    12.         return name;  
    13.     }  
    14.     public void setName(String name) {  
    15.         this.name = name;  
    16.     }  
    17.     public float getPrice() {  
    18.         return price;  
    19.     }  
    20.     public void setPrice(float price) {  
    21.         this.price = price;  
    22.     }  
    23.     @Override  
    24.     public String toString(){  
    25.         return this.id+":"+this.name+":"+this.price;  
    26.     }  
    27. }  

     

    测试使用单元测试如下ParseTest.java

    Java代码 
      1. public class ParseTest extends TestCase{  
      2.   
      3.     public void testDom() throws Exception{  
      4.         InputStream input = this.getClass().getClassLoader().getResourceAsStream("book.xml");  
      5.         DomParseService dom = new DomParseService();  
      6.         List<Book> books = dom.getBooks(input);  
      7.         for(Book book : books){  
      8.             System.out.println(book.toString());  
      9.         }  
      10.     }  
      11. }  
  • 相关阅读:
    Mybatis 原始dao CRUD方法
    JQuery的焦点事件focus() 与按键事件keydown() 及js判断当前页面是否为顶级页面 子页面刷新将顶级页面刷新 window.top.location
    使用actionerror做失败登录验证
    Java项目中的下载 与 上传
    shiro框架 4种授权方式 说明
    javascript 中数组的创建 添加 与将数组转换成字符串 页面三种提交请求的方式
    序列化表单为json对象,datagrid带额外参提交一次查询 后台用Spring data JPA 实现带条件的分页查询 多表关联查询
    Spring data JPA 理解(默认查询 自定义查询 分页查询)及no session 三种处理方法
    orcal 数据库 maven架构 ssh框架 的全注解环境模版 maven中央仓库批量删除lastupdated文件后依然是lastupdated解决方法 mirror aliyun中央仓库
    EasyUI加zTree使用解析 easyui修改操作的表单回显方法 验证框提交表单前验证 datagrid的load方法
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4325606.html
Copyright © 2011-2022 走看看