JAVA解析XML四種方法

XML現在已經成爲一種通用的數據交換格式,它的平臺無關性,語言無關性,系統無關性,給數據集成與交互帶來了極大的方便。對於XML本身的語法知識與技術細節,需要閱讀相關的技術文獻,這裏麪包括的內容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),具體可參閱w3c官方網站文檔http://www.w3.org獲取更多信息。

XML在不同的語言裏解析方式都是一樣的,只不過實現的語法不同而已。基本的解析方式有兩種,一種叫SAX,另一種叫DOMSAX是基於事件流的解析,DOM是基於XML文檔樹結構的解析。假設我們XML的內容和結構如下:

<?xml version="1.0" encoding="UTF-8"?>

<employees>

  <employee>

    <name>ddviplinux</name>

    <sex>m</sex>

    <age>30</age>

  </employee>

   <employee>

    <name>david</name>

    <sex>f</sex>

    <age>30</age>

  </employee>

</employees>

定義一個操作四種XML文檔的接口XmlDocument.java

 

  1. package com.alisoft.facepay.framework.bean;
  2. public interface XmlDocument {
  3. public void createXml(String fileName);
  4. public void parserXml(String fileName);
  5. }

1.

       DOM生成和解析XML文檔

XML 文檔的已解析版本定義了一組接口。解析器讀入整個文檔,然後構建一個駐留內存的樹結構,然後代碼就可以使用 DOM 接口來操作這個樹結構。優點:整個文檔樹在內存中,便於操作;支持刪除、修改、重新排列等多種功能;缺點:將整個文檔調入內存(包括無用的節點),浪費時間和空間;使用場合:一旦解析了文檔還需多次訪問這些數據;硬件資源充足(內存、CPU)。

 

 

  1. package com.alisoft.facepay.framework.bean;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.PrintWriter;
  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. import org.w3c.dom.Document;
  19. import org.w3c.dom.Element;
  20. import org.w3c.dom.Node;
  21. import org.w3c.dom.NodeList;
  22. import org.xml.sax.SAXException;
  23. public class DomDemo implements XmlDocument {
  24.     @SuppressWarnings("unused")
  25.     private Document document;
  26.     @SuppressWarnings("unused")
  27.     private String fileName;
  28.     public void init() {
  29.         try {
  30.             DocumentBuilderFactory factory = DocumentBuilderFactory
  31.                     .newInstance();
  32.             DocumentBuilder builder = factory.newDocumentBuilder();
  33.             this.document = builder.newDocument();
  34.         } catch (ParserConfigurationException e) {
  35.             System.out.println(e.getMessage());
  36.         }
  37.     }
  38.     public void createXml(String fileName) {
  39.         Element root = this.document.createElement("employees");
  40.         this.document.appendChild(root);
  41.         Element employee = this.document.createElement("employee");
  42.         Element name = this.document.createElement("name");
  43.         name.appendChild(this.document.createTextNode("丁宏亮"));
  44.         employee.appendChild(name);
  45.         Element sex = this.document.createElement("sex");
  46.         sex.appendChild(this.document.createTextNode("m"));
  47.         employee.appendChild(sex);
  48.         Element age = this.document.createElement("age");
  49.         age.appendChild(this.document.createTextNode("30"));
  50.         employee.appendChild(age);
  51.         root.appendChild(employee);
  52.         TransformerFactory tf = TransformerFactory.newInstance();
  53.         try {
  54.             Transformer transformer = tf.newTransformer();
  55.             DOMSource source = new DOMSource(document);
  56.             transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
  57.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  58.             PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
  59.             StreamResult result = new StreamResult(pw);
  60.             transformer.transform(source, result);
  61.             System.out.println("生成XML文件成功!");
  62.         } catch (TransformerConfigurationException e) {
  63.             System.out.println(e.getMessage());
  64.         } catch (IllegalArgumentException e) {
  65.             System.out.println(e.getMessage());
  66.         } catch (FileNotFoundException e) {
  67.             System.out.println(e.getMessage());
  68.         } catch (TransformerException e) {
  69.             System.out.println(e.getMessage());
  70.         }
  71.     }
  72.     public void parserXml(String fileName) {
  73.         try {
  74.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  75.             DocumentBuilder db = dbf.newDocumentBuilder();
  76.             Document document = db.parse(fileName);
  77.             NodeList employees = document.getChildNodes();
  78.             for (int i = 0; i < employees.getLength(); i++) {
  79.                 Node employee = employees.item(i);
  80.                 NodeList employeeInfo = employee.getChildNodes();
  81.                 for (int j = 0; j < employeeInfo.getLength(); j++) {
  82.                     Node node = employeeInfo.item(j);
  83.                     NodeList employeeMeta = node.getChildNodes();
  84.                     for (int k = 0; k < employeeMeta.getLength(); k++) {
  85.                         System.out.println(employeeMeta.item(k).getNodeName()
  86.                                 + ":" + employeeMeta.item(k).getTextContent());
  87.                     }
  88.                 }
  89.             }
  90.             System.out.println("解析完畢");
  91.         } catch (FileNotFoundException e) {
  92.             System.out.println(e.getMessage());
  93.         } catch (ParserConfigurationException e) {
  94.             System.out.println(e.getMessage());
  95.         } catch (SAXException e) {
  96.             System.out.println(e.getMessage());
  97.         } catch (IOException e) {
  98.             System.out.println(e.getMessage());
  99.         }
  100.     }
  101. }

2.

       SAX生成和解析XML文檔

    爲解決DOM的問題,出現了SAXSAX ,事件驅動。當解析器發現元素開始、元素結束、文本、文檔的開始或結束等時,發送事件,程序員編寫響應這些事件的代碼,保存數據。優點:不用事先調入整個文檔,佔用資源少;SAX解析器代碼比DOM解析器代碼小,適於Applet,下載。缺點:不是持久的;事件過後,若沒保存數據,那麼數據就丟了;無狀態性;從事件中只能得到文本,但不知該文本屬於哪個元素;使用場合:Applet;只需XML文檔的少量內容,很少回頭訪問;機器內存少;

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

 

 

 

  1. package com.alisoft.facepay.framework.bean;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import javax.xml.parsers.ParserConfigurationException;
  7. import javax.xml.parsers.SAXParser;
  8. import javax.xml.parsers.SAXParserFactory;
  9. import org.xml.sax.Attributes;
  10. import org.xml.sax.SAXException;
  11. import org.xml.sax.helpers.DefaultHandler;
  12. public class SaxDemo implements XmlDocument {
  13.     public void createXml(String fileName) {
  14.      
  15.     }
  16.     public void parserXml(String fileName) {
  17.         SAXParserFactory saxfac = SAXParserFactory.newInstance();
  18.         try {
  19.             SAXParser saxparser = saxfac.newSAXParser();
  20.             InputStream is = new FileInputStream(fileName);
  21.             saxparser.parse(isnew MySAXHandler());
  22.         } catch (ParserConfigurationException e) {
  23.             e.printStackTrace();
  24.         } catch (SAXException e) {
  25.             e.printStackTrace();
  26.         } catch (FileNotFoundException e) {
  27.             e.printStackTrace();
  28.         } catch (IOException e) {
  29.             e.printStackTrace();
  30.         }
  31.     }
  32. }
  33. class MySAXHandler extends DefaultHandler {
  34.     boolean hasAttribute = false;
  35.     Attributes attributes = null;
  36.     public void startDocument() throws SAXException {
  37.         System.out.println("文檔開始打印了");
  38.     }
  39.     public void endDocument() throws SAXException {
  40.         System.out.println("文檔打印結束了");
  41.     }
  42.     public void startElement(String uri, String localName, String qName,
  43.     Attributes attributes) throws SAXException {
  44.         if (qName.equals("employees")) {
  45.             return;
  46.         }
  47.         if (qName.equals("employee")) {
  48.             System.out.println(qName);
  49.         }
  50.         if (attributes.getLength() > 0) {
  51.             this.attributes = attributes;
  52.             this.hasAttribute = true;
  53.         }
  54.     }
  55.     public void endElement(String uri, String localName, String qName)
  56.     throws SAXException {
  57.         if (hasAttribute && (attributes != null)) {
  58.             for (int i = 0; i < attributes.getLength(); i++) {
  59.                 System.out.println(attributes.getQName(0)
  60.                         + attributes.getValue(0));
  61.             }
  62.         }
  63.     }
  64.     public void characters(char[] ch, int start, int length)
  65.     throws SAXException {
  66.         System.out.println(new String(ch, start, length));
  67.     }
  68. }

3.

       DOM4J生成和解析XML文檔

         DOM4J 是一個非常非常優秀的Java XML API,具有性能優異、功能強大和極端易用使用的特點,同時它也是一個開放源代碼的軟件。如今你可以看到越來越多的 Java 軟件都在使用 DOM4J 來讀寫 XML,特別值得一提的是連 Sun JAXM 也在用 DOM4J

 

 

 

  1. package com.alisoft.facepay.framework.bean;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.io.Writer;
  6. import java.util.Iterator;
  7. import org.dom4j.Document;
  8. import org.dom4j.DocumentException;
  9. import org.dom4j.DocumentHelper;
  10. import org.dom4j.Element;
  11. import org.dom4j.io.SAXReader;
  12. import org.dom4j.io.XMLWriter;
  13. public class Dom4jDemo implements XmlDocument {
  14.     public void createXml(String fileName) {
  15.         Document document = DocumentHelper.createDocument();
  16.         Element employees=document.addElement("employees");
  17.         Element employee=employees.addElement("employee");
  18.         Element name= employee.addElement("name");
  19.         name.setText("ddvip");
  20.         Element sex=employee.addElement("sex");
  21.         sex.setText("m");
  22.         Element age=employee.addElement("age");
  23.         age.setText("29");
  24.         try {
  25.             Writer fileWriter=new FileWriter(fileName);
  26.             XMLWriter xmlWriter=new XMLWriter(fileWriter);
  27.             xmlWriter.write(document);
  28.             xmlWriter.close();
  29.         } catch (IOException e) {
  30.             
  31.             System.out.println(e.getMessage());
  32.         }
  33.         
  34.         
  35.     }
  36.     public void parserXml(String fileName) {
  37.          File inputXml=new File(fileName);
  38.          SAXReader saxReader = new SAXReader();
  39.          try {
  40.             Document document = saxReader.read(inputXml);
  41.             Element employees=document.getRootElement();
  42.             for(Iterator i = employees.elementIterator(); i.hasNext();){
  43.                  Element employee = (Element) i.next();
  44.                  for(Iterator j = employee.elementIterator(); j.hasNext();){
  45.                      Element node=(Element) j.next();
  46.                      System.out.println(node.getName()+":"+node.getText());
  47.                  }
  48.             }
  49.         } catch (DocumentException e) {
  50.             System.out.println(e.getMessage());
  51.         }
  52.      System.out.println("dom4j parserXml");
  53.     }
  54. }

 

4.       JDOM生成和解析XML

爲減少DOMSAX的編碼量,出現了JDOM;優點:20-80原則,極大減少了代碼量。使用場合:要實現的功能簡單,如解析、創建等,但在底層,JDOM還是使用SAX(最常用)、DOMXanan文檔。

 

 

 

 

 

  1. package com.alisoft.facepay.framework.bean;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.List;
  6. import org.jdom.Document;
  7. import org.jdom.Element;
  8. import org.jdom.JDOMException;
  9. import org.jdom.input.SAXBuilder;
  10. import org.jdom.output.XMLOutputter;
  11. public class JDomDemo implements XmlDocument {
  12.     public void createXml(String fileName) {
  13.       Document document;
  14.       Element  root;
  15.       root=new Element("employees");
  16.       document=new Document(root);
  17.       Element employee=new Element("employee");
  18.       root.addContent(employee);
  19.       Element name=new Element("name");
  20.       name.setText("ddvip");
  21.       employee.addContent(name);
  22.       Element sex=new Element("sex");
  23.       sex.setText("m");
  24.       employee.addContent(sex);
  25.       Element age=new Element("age");
  26.       age.setText("23");
  27.       employee.addContent(age);
  28.       XMLOutputter XMLOut = new XMLOutputter();
  29.       try {
  30.         XMLOut.output(document, new FileOutputStream(fileName));
  31.     } catch (FileNotFoundException e) {
  32.         e.printStackTrace();
  33.     } catch (IOException e) {
  34.         e.printStackTrace();
  35.     }
  36.     }
  37.     public void parserXml(String fileName) {
  38.         SAXBuilder builder=new SAXBuilder(false); 
  39.         try {
  40.             Document document=builder.build(fileName);
  41.             Element employees=document.getRootElement(); 
  42.             List employeeList=employees.getChildren("employee");
  43.             for(int i=0;i<employeeList.size();i++){
  44.                 Element employee=(Element)employeeList.get(i);
  45.                 List employeeInfo=employee.getChildren();
  46.                 for(int j=0;j<employeeInfo.size();j++){
  47.                     System.out.println(((Element)employeeInfo.get(j)).getName()+":"+((Element)employeeInfo.get(j)).getValue());
  48.                     
  49.                 }
  50.             }
  51.         } catch (JDOMException e) {
  52.         
  53.             e.printStackTrace();
  54.         } catch (IOException e) {
  55.         
  56.             e.printStackTrace();
  57.         } 
  58.     }
  59. }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章