XML 的解析方法

 

四种XML解析方法:

   (1)Dom生成和解析XML文档

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

   (2)SAX生成和解析XML文档

      * SAX ,事件驱动。
     * 当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。
     * 优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。
     * 缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;
     * 无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;
     * 使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少; 

   (3)DOM4J生成和解析XML文档

      * DOM4J 是一个非常非常优秀的Java XML API,
     * 具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。
     * 如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。

   (4)JDOM生成和解析XML

       *为减少DOM、SAX的编码量,出现了JDOM;
     *优点:20-80原则,极大减少了代码量。
     *使用场合:要实现的功能简单,如解析、创建等,
     *但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。 

 

 

首先编写一个要解析的test.xml文件

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
  2. <employees>  
  3. <employee>  
  4. <name>wxyfree</name>  
  5. <age>30</age>  
  6. </employee>  
  7. <employee>  
  8. <name>freewxy</name>  
  9. <age>22</age>  
  10. </employee>  
  11. </employees>  

 

然后,编写一个XMLDocument接口

Java代码  收藏代码
  1. /** 
  2.  * 定义XML文档建立与解析的接口 
  3.  * @author wxy 
  4.  * 
  5.  */  
  6. public interface XMLDocument {  
  7.     /** 
  8.      *建立XML文档  
  9.      * @param fileName 文件全路径名 
  10.      */  
  11.     public void createXML(String fileName);  
  12.     /** 
  13.      * 解析XML文档 
  14.      * @param fileName 文件全路径名 
  15.      */  
  16.     public void parseXML(String fileName);  
  17. }  

 

一、

Java代码  收藏代码
  1. package review.testXML;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  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.   
  20. import org.w3c.dom.Document;  
  21. import org.w3c.dom.Element;  
  22. import org.w3c.dom.Node;  
  23. import org.w3c.dom.NodeList;  
  24. import org.xml.sax.SAXException;  
  25.   
  26.   
  27.   
  28. /** 
  29.  * Dom生成和解析XML文档 
  30.  * 为 XML 文档的已解析版本定义了一组接口。 
  31.  * 解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。 
  32.  * 优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能; 
  33.  * 缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间; 
  34.  * 使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。  
  35.  * @param args 
  36.  */  
  37. public class DomDemo implements XMLDocument  {  
  38.   
  39.     private Document document;  
  40.     private String fileName;  
  41.       
  42.     public void init(){  
  43.         try{  
  44.             DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();  
  45.             DocumentBuilder builder=factory.newDocumentBuilder();  
  46.             this.document=builder.newDocument();  
  47.         }catch(ParserConfigurationException e){  
  48.             System.out.println(e.getMessage());  
  49.         }  
  50.     }  
  51.     @Override  
  52.     public void createXML(String fileName) {  
  53.         Element root=this.document.createElement("employees");//创建根元素  
  54.         this.document.appendChild(root);  
  55.         Element employee=this.document.createElement("employee");//创建子元素  
  56.         Element name=this.document.createElement("name");//添加元素的属性  
  57.         name.appendChild(this.document.createTextNode("wxyfree"));  
  58.         employee.appendChild(name);//将元素添加到子元素中  
  59.         Element sex=this.document.createElement("sex");  
  60.         sex.appendChild(this.document.createTextNode("m"));  
  61.         Element age=this.document.createElement("age");  
  62.         age.appendChild(this.document.createTextNode("30"));  
  63.         employee.appendChild(age);  
  64.         root.appendChild(employee);//将子元素添加到根元素中  
  65.         TransformerFactory tf=TransformerFactory.newInstance();//此抽象类的实例能够将源树转为结果树  
  66.         try{  
  67.             Transformer transformer=tf.newTransformer();  
  68.             DOMSource source=new DOMSource(document);//创建带有DOM节点的新输入源  
  69.             transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");//设置转换中世纪的输出属性  
  70.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");//  
  71.             PrintWriter pw=new PrintWriter(new FileOutputStream(fileName));  
  72.             StreamResult result=new StreamResult(pw);//充当转换结果的持有者,可以为xml、纯文本、HTML或某些其他格式的标记  
  73.             transformer.transform(source, result);//将XML Source转换为Result  
  74.             System.out.println("生成XML文件成功");  
  75.         }catch(TransformerConfigurationException e){  
  76.             System.out.println(e.getMessage());  
  77.         } catch (TransformerException e) {  
  78.             System.out.println(e.getMessage());  
  79.         } catch (FileNotFoundException e) {  
  80.             System.out.println(e.getMessage());  
  81.         }  
  82.     }  
  83.   
  84.     @Override  
  85.     public void parseXML(String fileName) {  
  86.         DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();  
  87.         DocumentBuilder db;  
  88.         try {  
  89.             db = dbf.newDocumentBuilder();  
  90.             Document document = db.parse(fileName);  
  91.             NodeList employees=document.getChildNodes();  
  92.             for(int i=0;i<employees.getLength();i++){  
  93.                 Node employee=employees.item(i);  
  94.                 NodeList employeeInfo=employee.getChildNodes();  
  95.                 for(int j=0;j<employeeInfo.getLength();j++){  
  96.                     Node node=employeeInfo.item(j);  
  97.                     NodeList employeeMeta=node.getChildNodes();  
  98.                     for(int k=0;k<employeeMeta.getLength();k++){  
  99.                         System.out.println(employeeMeta.item(k).getNodeName()+":"+employeeMeta.item(k).getTextContent());  
  100.                     }  
  101.                 }  
  102.             }  
  103.         } catch (ParserConfigurationException e) {  
  104.             // TODO Auto-generated catch block  
  105.             e.printStackTrace();  
  106.         } catch (SAXException e) {  
  107.             // TODO Auto-generated catch block  
  108.             e.printStackTrace();  
  109.         } catch (IOException e) {  
  110.             // TODO Auto-generated catch block  
  111.             e.printStackTrace();  
  112.         }  
  113.         System.out.println("解析完毕");  
  114.     }  
  115.   
  116.     public static void main(String[] args){  
  117.         DomDemo d=new DomDemo();  
  118.         d.init();  
  119.         d.createXML("conf/test2.xml");  
  120.         d.parseXML("conf/test.xml");  
  121.   
  122.     }  
  123.   
  124. }  

 

 

二、

Java代码  收藏代码
  1. package review.testXML;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7.   
  8. import javax.xml.parsers.ParserConfigurationException;  
  9. import javax.xml.parsers.SAXParser;  
  10. import javax.xml.parsers.SAXParserFactory;  
  11.   
  12. import org.xml.sax.Attributes;  
  13. import org.xml.sax.HandlerBase;  
  14. import org.xml.sax.SAXException;  
  15. import org.xml.sax.helpers.DefaultHandler;  
  16.   
  17. /** 
  18.  * SAX ,事件驱动。 
  19.  * 当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。 
  20.  * 优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。 
  21.  * 缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了; 
  22.  *      无状态性;从事件中只能得到文本,但不知该文本属于哪个元素; 
  23.  * 使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;  
  24.  * @author wxy 
  25.  * 
  26.  */  
  27. public class SaxDemo implements XMLDocument{  
  28.   
  29.     @Override  
  30.     public void createXML(String fileName) {  
  31.         System.out.println("<<"+fileName+">>");  
  32.           
  33.     }  
  34.   
  35.     @Override  
  36.     public void parseXML(String fileName) {  
  37.         SAXParserFactory saxfac=SAXParserFactory.newInstance();  
  38.         try {  
  39.             SAXParser saxParser=saxfac.newSAXParser();  
  40.             InputStream ins=new FileInputStream(fileName);  
  41.             saxParser.parse(ins,new MySAXHandler());  
  42.         } catch (ParserConfigurationException e) {  
  43.             System.out.println(e.getMessage());  
  44.         } catch (SAXException e) {  
  45.             System.out.println(e.getMessage());  
  46.         } catch (FileNotFoundException e) {  
  47.             System.out.println(e.getMessage());  
  48.         } catch (IOException e) {  
  49.             System.out.println(e.getMessage());  
  50.         }  
  51.           
  52.     }  
  53.     /** 
  54.      * @param args 
  55.      */  
  56.     public static void main(String[] args) {  
  57.      SaxDemo s=new SaxDemo();  
  58.      s.parseXML("conf/test.xml");  
  59.     }  
  60. }  
  61. class MySAXHandler extends DefaultHandler{  
  62.     boolean hasAttribute=false;  
  63.     Attributes attributes=null;  
  64.       
  65.     /** 
  66.      *  Receive notification of the beginning of the document. 
  67.      */  
  68.     public void startDocument()throws SAXException{  
  69.         System.out.print("文档开始打印了");  
  70.     }  
  71.     /** 
  72.      * Receive notification of the end of the document. 
  73.      */  
  74.     public void endDocument()throws SAXException{  
  75.         System.out.print("文档开始结束了");   
  76.     }  
  77.      /** 
  78.      * Receive notification of the start of an element. 
  79.      * @param uri The Namespace URI, or the empty string if the 
  80.      *        element has no Namespace URI or if Namespace 
  81.      *        processing is not being performed. 
  82.      * @param localName The local name (without prefix), or the 
  83.      *        empty string if Namespace processing is not being 
  84.      *        performed. 
  85.      * @param qName The qualified name (with prefix), or the 
  86.      *        empty string if qualified names are not available. 
  87.      * @param attributes The attributes attached to the element.  If 
  88.      *        there are no attributes, it shall be an empty 
  89.      *        Attributes object. 
  90.      * @exception org.xml.sax.SAXException Any SAX exception, possibly 
  91.      *            wrapping another exception. 
  92.      */  
  93.     public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException{  
  94.         if(qName.equals("employees")){return;}  
  95.         if(qName.equals("employee")){  
  96.             System.out.print(qName);  
  97.         }  
  98.         if(attributes.getLength()>0){  
  99.             this.attributes=attributes;  
  100.             this.hasAttribute=true;  
  101.         }  
  102.     }  
  103.     /** 
  104.      * Receive notification of the end of an element. 
  105.      * @param uri The Namespace URI, or the empty string if the 
  106.      *        element has no Namespace URI or if Namespace 
  107.      *        processing is not being performed. 
  108.      * @param localName The local name (without prefix), or the 
  109.      *        empty string if Namespace processing is not being 
  110.      *        performed. 
  111.      * @param qName The qualified name (with prefix), or the 
  112.      *        empty string if qualified names are not available. 
  113.      * @exception org.xml.sax.SAXException Any SAX exception, possibly 
  114.      *            wrapping another exception. 
  115.      */  
  116.     public void endElement(String uri,String localName,String qNaqme)throws SAXException{  
  117.         if(hasAttribute&&(attributes!=null)){  
  118.             for(int i=0;i<attributes.getLength();i++){  
  119.                 System.out.print(attributes.getQName(0)+attributes.getValue(0));  
  120.             }  
  121.         }  
  122.     }  
  123.     /** 
  124.      * Receive notification of character data inside an element. 
  125.      * @param ch The characters. 
  126.      * @param start The start position in the character array. 
  127.      * @param length The number of characters to use from the 
  128.      *               character array. 
  129.      */  
  130.     public void characters(char[] ch,int start,int length)throws SAXException{  
  131.         System.out.print(new String(ch,start,length));  
  132.     }  
  133. }  

 

三、

Java代码  收藏代码
  1. package review.testXML;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.Writer;  
  7. import java.util.Iterator;  
  8.   
  9. import org.dom4j.Document;  
  10. import org.dom4j.DocumentException;  
  11. import org.dom4j.DocumentHelper;  
  12. import org.dom4j.Element;  
  13. import org.dom4j.io.SAXReader;  
  14. import org.dom4j.io.XMLWriter;  
  15.   
  16. /** 
  17.  *  Dom4j 生成XML文档与解析XML文档 
  18.  * DOM4J 是一个非常非常优秀的Java XML API, 
  19.  * 具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。 
  20.  * 如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。  
  21.  * @author wxy 
  22.  * 
  23.  */  
  24. public class Dom4jDemo implements XMLDocument{  
  25.   
  26.     @Override  
  27.     public void createXML(String fileName) {  
  28.         Document document = DocumentHelper.createDocument();  
  29.         Element employees=document.addElement("employees");  
  30.         Element employee=document.addElement("employee");  
  31.         Element name=employee.addElement("name");  
  32.         name.setText("wxy");  
  33.         Element sex=employee.addElement("sex");  
  34.         name.setText("f");  
  35.         Element age=employee.addElement("age");  
  36.         name.setText("29");  
  37.         try {  
  38.             Writer fileWriter=new FileWriter(fileName);  
  39.             XMLWriter xmlWriter=new XMLWriter(fileWriter);  
  40.             xmlWriter.write(document);  
  41.             xmlWriter.close();  
  42.         } catch (IOException e) {  
  43.             System.out.println(e.getMessage());  
  44.         }  
  45.     }  
  46.   
  47.     @Override  
  48.     public void parseXML(String fileName) {  
  49.         File inputXML=new File(fileName);  
  50.         SAXReader saxReader=new SAXReader();  
  51.         try {  
  52.             Document document=saxReader.read(inputXML);  
  53.             Element employees=document.getRootElement();  
  54.             for(Iterator i=employees.elementIterator();i.hasNext();){  
  55.                 Element employee=(Element)i.next();  
  56.                 for(Iterator j=employee.elementIterator();j.hasNext();){  
  57.                     Element node=(Element)j.next();  
  58.                     System.out.println(node.getName()+":"+node.getText());    
  59.                 }  
  60.             }  
  61.         } catch (DocumentException e) {  
  62.             System.out.println(e.getMessage());  
  63.         }  
  64.         System.out.println("dom4j parserXML");  
  65.     }  
  66.   
  67.       
  68.     public static void main(String[] args) {  
  69.         Dom4jDemo d=new Dom4jDemo();  
  70.         d.parseXML("conf/test.xml");  
  71.     }  
  72.   
  73. }  

 

 

四、

Java代码  收藏代码
  1. package review.testXML;  
  2.   
  3.   
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.util.List;  
  8.   
  9. import org.jdom.Document;  
  10. import org.jdom.Element;  
  11. import org.jdom.JDOMException;  
  12. import org.jdom.input.SAXBuilder;  
  13. import org.jdom.output.XMLOutputter;  
  14.   
  15.   
  16. /** 
  17.  * JDOM生成和解析XML    
  18.  *为减少DOM、SAX的编码量,出现了JDOM; 
  19.  *优点:20-80原则,极大减少了代码量。 
  20.  *使用场合:要实现的功能简单,如解析、创建等, 
  21.  *但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。  
  22.  * @author wxy 
  23.  * 
  24.  */  
  25. public class JDomDemo implements XMLDocument{  
  26.       
  27.   
  28.     @Override  
  29.     public void createXML(String fileName) {  
  30.         Document document;  
  31.         Element root;  
  32.         root=new Element("employees");  
  33.         document=new Document(root);  
  34.         Element employee=new Element("employee");  
  35.         root.addContent(employee);  
  36.         Element name=new Element("name");  
  37.         name.setText("wxywxy");  
  38.         employee.addContent(name);  
  39.         Element sex=new Element("sex");  
  40.         sex.setText("m");  
  41.         employee.addContent(sex);  
  42.         Element age=new Element("age");  
  43.         age.setText("25");  
  44.         employee.addContent(age);  
  45.         XMLOutputter XMLOut=new XMLOutputter();  
  46.         try {  
  47.             XMLOut.output(document, new FileOutputStream(fileName));  
  48.         } catch (FileNotFoundException e) {  
  49.             System.out.println(e.getMessage());  
  50.         } catch (IOException e) {  
  51.             System.out.println(e.getMessage());  
  52.         }  
  53.     }  
  54.   
  55.     @Override  
  56.     public void parseXML(String fileName) {  
  57.         SAXBuilder builder=new SAXBuilder(false);  
  58.         try {  
  59.             Document document=builder.build(fileName);  
  60.             Element employees=document.getRootElement();  
  61.             List employeeList=employees.getChildren("employee");  
  62.             for(int i=0;i<employeeList.size();i++){  
  63.                 Element employee=(Element)employeeList.get(i);  
  64.                 List employeeInfo=employee.getChildren();  
  65.                 for(int j=0;j<employeeInfo.size();j++){  
  66.                     System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getText());  
  67.                 }  
  68.             }  
  69.         } catch (JDOMException e) {  
  70.             System.out.println(e.getMessage());  
  71.         } catch (IOException e) {  
  72.             System.out.println(e.getMessage());  
  73.         }  
  74.     }  
  75.   
  76.       
  77.     public static void main(String[] args){  
  78.         JDomDemo jd=new JDomDemo();  
  79.         jd.parseXML("conf/test.xml");  
  80.     }  
  81. }  

 

posted @ 2017-08-10 15:55  就是你baby  阅读(353)  评论(0编辑  收藏  举报