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. {   
  17.     public List<Book> getBooks(InputStream inputStream) throws Exception
  18.     {   
  19.         List<Book> list = new ArrayList<Book>();   
  20.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
  21.         DocumentBuilder builder = factory.newDocumentBuilder();   
  22.         Document document = builder.parse(inputStream);   
  23.         Element element = document.getDocumentElement();   
  24.            
  25.         NodeList bookNodes = element.getElementsByTagName("book");   
  26.         for(int i=0;i<bookNodes.getLength();i++){   
  27.             Element bookElement = (Element) bookNodes.item(i);   
  28.             Book book = new Book();   
  29.             book.setId(Integer.parseInt(bookElement.getAttribute("id")));   
  30.             NodeList childNodes = bookElement.getChildNodes();   
  31. //          System.out.println("*****"+childNodes.getLength());  
  32.             for(int j=0;j<childNodes.getLength();j++)
  33.             {   
  34.                 if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
  35.                 {   
  36.                     if("name".equals(childNodes.item(j).getNodeName()))
  37.                     {   
  38.                         book.setName(childNodes.item(j).getFirstChild().getNodeValue());   
  39.                     }
  40.                     else if("price".equals(childNodes.item(j).getNodeName()))
  41.                    {   
  42.                         book.setPrice(Float.parseFloat(childNodes.item(j).getFirstChild().getNodeValue()));   
  43.                     }   
  44.                 }   
  45.             }    //end for j  
  46.             list.add(book);   
  47.         }    //end for i  
  48.         return list;   
  49.     }   
  50. }  

 

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

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

 

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

Java代码   
  1. public class ParseTest extends TestCase
  2.     public void testDom() throws Exception
  3.     {   
  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.         {   
  9.             System.out.println(book.toString());   
  10.         }   
  11.     }   
  12. }  

 

原打算将dom解析和Sax解析写在一起的,没想到超过字数了,只能分开写了,如果对Sax解析感兴趣,可以到下面的链接去看:http://sinye.iteye.com/blog/763895

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用DOM解析XML的示例代码,假设我们要解析如下的XML文档: ```xml <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="children"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> ``` 解析代码如下: ```java import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class DomParserExample { public static void main(String[] args) { try { File inputFile = new File("input.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("book"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Category : " + eElement.getAttribute("category")); System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent()); System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent()); System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent()); System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } } ``` 运行以上代码,输出如下: ``` Root element :bookstore ---------------------------- Current Element :book Category : children Title : Harry Potter Author : J.K. Rowling Year : 2005 Price : 29.99 Current Element :book Category : web Title : Learning XML Author : Erik T. Ray Year : 2003 Price : 39.95 ``` 以上代码使用了Java标准库中的DOM解析器,首先通过`DocumentBuilderFactory`和`DocumentBuilder`创建解析器实例,然后使用`parse`方法解析XML文档。接着遍历XML文档中的所有`book`元素,获取元素节点的属性和子节点的文本内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值