java与xml之DOM创建和解析XML文档

来源:互联网 发布:java string contact 编辑:程序博客网 时间:2024/06/05 02:39
     DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准。DOM是以层次结构组织的节点或信息片断的集合。这个层次结构允许开发人员在树中寻找特定信息。分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作。由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的。DOM 

以及广义的基于树的处理具有几个优点。首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改。它还可以在任何时候在树中上下导航,而不是像SAX那样是一次性的处理。DOM使用起来也要简单得多。

       为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。

优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;
缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。 

废话不多说,上代码:

[java] view plain copy
  1. package com.mdy.xml.xmldemo;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import javax.xml.parsers.DocumentBuilder;  
  9. import javax.xml.parsers.DocumentBuilderFactory;  
  10. import javax.xml.parsers.ParserConfigurationException;  
  11. import javax.xml.transform.OutputKeys;  
  12. import javax.xml.transform.Transformer;  
  13. import javax.xml.transform.TransformerConfigurationException;  
  14. import javax.xml.transform.TransformerException;  
  15. import javax.xml.transform.TransformerFactory;  
  16. import javax.xml.transform.dom.DOMSource;  
  17. import javax.xml.transform.stream.StreamResult;  
  18.   
  19. import org.w3c.dom.Document;  
  20. import org.w3c.dom.Element;  
  21. import org.w3c.dom.NamedNodeMap;  
  22. import org.w3c.dom.Node;  
  23. import org.w3c.dom.NodeList;  
  24. import org.xml.sax.SAXException;  
  25.   
  26. public class DomDemo{  
  27.   
  28.     private Document document;  
  29.       
  30.     public DomDemo() {  
  31.         super();  
  32.         DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance() ;  
  33.         DocumentBuilder dBuilder;  
  34.         try {  
  35.             dBuilder = DBF.newDocumentBuilder();  
  36.             document = dBuilder.newDocument();  
  37.             document.createComment("书籍列表");  
  38.         } catch (ParserConfigurationException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42.       
  43.     public static void main(String[] args) {  
  44.         String fileName = "domDemo.xml";  
  45.         DomDemo domDemo = new DomDemo();  
  46.         domDemo.createXML(fileName);  
  47.         domDemo.parserXML(fileName);  
  48.     }  
  49.   
  50.     public void createXML(String fileName) {  
  51.         Element root = document.createElement("books");  
  52.         document.appendChild(root);  
  53.         // 循环创建三本书  
  54.         for(int i = 0;i<3;i++){  
  55.             Element book = document.createElement("book");  
  56.             book.setAttribute("id", i+1+"");  
  57.             Element bookName = document.createElement("name");  
  58.             Node nameNode = document.createTextNode("书本"+i);  
  59.             bookName.appendChild(nameNode);  
  60.             Element bookPrice = document.createElement("price");  
  61.             Node priceNode = document.createTextNode((i+1)*50+"");  
  62.             bookPrice.appendChild(priceNode);  
  63.             Element bookAuthor = document.createElement("author");  
  64.             Node authorNode = document.createTextNode("作者"+i);  
  65.             bookAuthor.appendChild(authorNode);  
  66.             book.appendChild(bookName);  
  67.             book.appendChild(bookPrice);  
  68.             book.appendChild(bookAuthor);  
  69.             root.appendChild(book);  
  70.         }  
  71.         TransformerFactory trf = TransformerFactory.newInstance();  
  72.         try {  
  73.             Transformer tf = trf.newTransformer();  
  74.             tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
  75.             tf.setOutputProperty(OutputKeys.INDENT, "yes");  
  76.             DOMSource xmlSource = new DOMSource(document);  
  77.               
  78.             StreamResult result = new StreamResult(new FileOutputStream(new  File(fileName)));  
  79.             tf.transform(xmlSource, result);  
  80.             System.out.println("生成XML成功");  
  81.         } catch (TransformerConfigurationException e) {  
  82.             e.printStackTrace();  
  83.         } catch (TransformerException e) {  
  84.             e.printStackTrace();  
  85.         } catch (FileNotFoundException e) {  
  86.             e.printStackTrace();  
  87.         }  
  88.     }  
  89.   
  90.     public void parserXML(String fileName) {  
  91.         DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance() ;  
  92.         DocumentBuilder dBuilder;  
  93.         try {  
  94.             dBuilder = DBF.newDocumentBuilder();  
  95.             Document documet = dBuilder.parse(fileName);  
  96.             NodeList nodeList = documet.getChildNodes();  
  97.             int size = nodeList.getLength();  
  98.             for(int n=0; n<size;n++){  
  99.                 getNode(nodeList.item(n));  
  100.             }  
  101.         } catch (ParserConfigurationException e) {  
  102.             e.printStackTrace();  
  103.         } catch (SAXException e) {  
  104.             e.printStackTrace();  
  105.         } catch (IOException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.     }  
  109.   
  110.     public void getNode(Node node){  
  111.         if(node != null && (node.getNodeType() == Node.ELEMENT_NODE)){  
  112.             System.out.println("-----------------------");  
  113.             String elementName = node.getNodeName();  
  114.             System.out.println("解析节点:"+elementName);  
  115.             NodeList list = node.getChildNodes();  
  116.             //解析节点属性  
  117.             NamedNodeMap map = node.getAttributes();  
  118.             int len = map.getLength();  
  119.             for(int i = 0;i<len;i++){  
  120.                 Node attribute = map.item(i);  
  121.                 System.out.println("属性\""+attribute.getNodeName()+"\"的值为"+attribute.getNodeValue());  
  122.             }  
  123.             for(int j = 0;j<=list.getLength();j++){  
  124.                 getNode(list.item(j));  
  125.             }  
  126.         }else if(node != null && (node.getNodeType() == Node.TEXT_NODE)){  
  127.             String elementValue = node.getTextContent();  
  128.             if(elementValue != null){  
  129.                 elementValue.replaceAll("\r\n""");  
  130.             }  
  131.             if(elementValue != null &&!"".equals(elementValue.trim())){  
  132.                 System.out.println("节点值为:"+node.getTextContent());  
  133.             }  
  134.         }  
  135.     }  
  136. }  

在main方法中,我们创建了一个domDemo.xml文件,然后进行了解析,打开生成的domDemo.xml文件,我们看到如下:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8" standalone="no"?>  
  2. <books>  
  3. <book id="1">  
  4. <name>书本0</name>  
  5. <price>50</price>  
  6. <author>作者0</author>  
  7. </book>  
  8. <book id="2">  
  9. <name>书本1</name>  
  10. <price>100</price>  
  11. <author>作者1</author>  
  12. </book>  
  13. <book id="3">  
  14. <name>书本2</name>  
  15. <price>150</price>  
  16. <author>作者2</author>  
  17. </book>  
  18. </books>  


解析后:结果如下:

生成XML成功
-----------------------
解析节点:books
-----------------------
解析节点:book
属性"id"的值为1
-----------------------
解析节点:name
节点值为:书本0
-----------------------
解析节点:price
节点值为:50
-----------------------
解析节点:author
节点值为:作者0
-----------------------
解析节点:book
属性"id"的值为2
-----------------------
解析节点:name
节点值为:书本1
-----------------------
解析节点:price
节点值为:100
-----------------------
解析节点:author
节点值为:作者1
-----------------------
解析节点:book
属性"id"的值为3
-----------------------
解析节点:name
节点值为:书本2
-----------------------
解析节点:price
节点值为:150
-----------------------
解析节点:author
节点值为:作者2

原创粉丝点击