xml的四種解析方法及源代碼(SAX、DOM、JDOM、DOM4J)

這個也是自己轉載的,現在對DOM還比較熟悉,自己不要只是複製代碼,可以試着去熟悉其中的一兩種,以後會有用處的。

xml的四種解析方法及源代碼(SAX、DOM、JDOM、DOM4J)

第一種:SAX解析 
SAX處理機制:SAX是一種基於事件驅動的API。利用SAX解析XML文檔,牽涉到兩個部分:解析器和事件處理器。解析器負責讀取XML文檔,並向事件處理器發生事件,如元素開始和元素結束事件;而事件處理器則負責對事件做出響應,對傳遞的XML數據進行處理。

測試用的xml文件:db.xml

Xml代碼 

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

<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->  

<dbconfig>  

 <db type="oracle">  

  <driver>oracle.jdbc.driver.OracleDriver</driver>  

  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>  

  <user>scott</user>  

  <password>tiger</password>  

 </db>  

</dbconfig>  

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

<!--<!DOCTYPE dbconfig SYSTEM "db.dtd">-->

<dbconfig>

 <db type="oracle">

  <driver>oracle.jdbc.driver.OracleDriver</driver>

  <url>jdbc:oracle:thin:@localhost:1521:oracle</url>

  <user>scott</user>

  <password>tiger</password>

 </db>

</dbconfig>

DTD文件db.dtd

Xml代碼 

  1. <!ELEMENT dbconfig (db+)>    
  2.   
  3. <!ELEMENT db (driver,url,user,password)>    
  4.   
  5. <!ELEMENT driver (#PCDATA)>    
  6.   
  7. <!ELEMENT url (#PCDATA)>    
  8.   
  9. <!ELEMENT user (#PCDATA)>    
  10.   
  11. <!ELEMENT password (#PCDATA)>    
  12.   
  13. <!ATTLIST db type CDATA #REQUIRED>    
  14.   
  15. <!ELEMENT dbconfig (db+)>  
  16.   
  17. <!ELEMENT db (driver,url,user,password)>  
  18.   
  19. <!ELEMENT driver (#PCDATA)>  
  20.   
  21. <!ELEMENT url (#PCDATA)>  
  22.   
  23. <!ELEMENT user (#PCDATA)>  
  24.   
  25. <!ELEMENT password (#PCDATA)>  
  26.   
  27. <!ATTLIST db type CDATA #REQUIRED>  


 

SAX解析實例一
org.xml.sax.DefalutHandler類:  可以擴展該類,給出自己的解析實現
SAXPrinter.java

Java代碼 

  1. import java.io.File;     
  2.   
  3.     
  4.   
  5. import javax.xml.parsers.SAXParser;     
  6.   
  7. import javax.xml.parsers.SAXParserFactory;     
  8.   
  9.     
  10.   
  11. import org.xml.sax.Attributes;     
  12.   
  13. import org.xml.sax.SAXException;     
  14.   
  15. import org.xml.sax.helpers.DefaultHandler;     
  16.   
  17.     
  18.   
  19. public class SAXPrinter extends DefaultHandler     
  20.   
  21. {     
  22.   
  23.     
  24.   
  25.   /** *//**    
  26.   
  27.    * 文檔開始事件    
  28.   
  29.    */    
  30.   
  31.     public void startDocument() throws SAXException     
  32.   
  33.     {     
  34.   
  35.         System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");     
  36.   
  37.     }     
  38.   
  39.          
  40.   
  41.   /** *//**    
  42.   
  43.    * 接收處理指令事件    
  44.   
  45.    */    
  46.   
  47.     public void processingInstruction(String target, String data) throws SAXException     
  48.   
  49.     {     
  50.   
  51.         System.out.println("<?"+target+" "+data+"?>");     
  52.   
  53.     }     
  54.   
  55.          
  56.   
  57.   /** *//**    
  58.   
  59.    * 元素開始事件    
  60.   
  61.    * 參數說明:    
  62.   
  63.    *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執行名稱空間處理,則爲空字符串。    
  64.   
  65.    *   localName - 本地名稱(不帶前綴),如果沒有正在執行名稱空間處理,則爲空字符串。    
  66.   
  67.    *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則爲空字符串。    
  68.   
  69.    *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。    
  70.   
  71.    */    
  72.   
  73.     public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException     
  74.   
  75.     {     
  76.   
  77.         System.out.print("<"+qName);//輸出元素名稱     
  78.   
  79.         int len=attrs.getLength();//元素屬性列表長度     
  80.   
  81.              
  82.   
  83.     //利用循環輸出屬性列表     
  84.   
  85.         for(int i=0;i<len;i++)     
  86.   
  87.         {     
  88.   
  89.             System.out.print(" ");     
  90.   
  91.             System.out.print(attrs.getQName(i));     
  92.   
  93.             System.out.print("=\"");     
  94.   
  95.             System.out.print(attrs.getValue(i));     
  96.   
  97.             System.out.print("\"");     
  98.   
  99.         }     
  100.   
  101.         System.out.print(">");     
  102.   
  103.     }     
  104.   
  105.          
  106.   
  107.   /** *//**    
  108.   
  109.    * 元素中字符數據事件:接收元素中字符數據    
  110.   
  111.    * 注意:1.應用程序不要試圖讀取ch數組指定範圍外的數據,(即start至length之外)    
  112.   
  113.    *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內容中的空白,而不是characters()方法,如:進行有效性驗證的解析器    
  114.   
  115.    */    
  116.   
  117.     public void characters(char[] ch, int start, int length) throws SAXException     
  118.   
  119.     {     
  120.   
  121.         System.out.print(new String(ch,start,length));     
  122.   
  123.     }     
  124.   
  125.     
  126.   
  127.   /** *//**    
  128.   
  129.    * 結束元素事件    
  130.   
  131.    */    
  132.   
  133.     public void endElement(String uri, String localName, String qName) throws SAXException     
  134.   
  135.     {     
  136.   
  137.         System.out.print("</"+qName+">");     
  138.   
  139.     }     
  140.   
  141.     
  142.   
  143.     public static void main(String[] args)     
  144.   
  145.     {     
  146.   
  147.         SAXParserFactory spf=SAXParserFactory.newInstance();     
  148.   
  149.              
  150.   
  151.         try    
  152.   
  153.         {     
  154.   
  155.             SAXParser sp=spf.newSAXParser();     
  156.   
  157.             sp.parse(new File("db.xml"),new SAXPrinter());     
  158.   
  159.         }     
  160.   
  161.         catch (Exception e)     
  162.   
  163.         {     
  164.   
  165.             e.printStackTrace();     
  166.   
  167.         }     
  168.   
  169.     }     
  170.   
  171. }    
  172.   
  173. import java.io.File;  
  174.   
  175.   
  176. import javax.xml.parsers.SAXParser;  
  177.   
  178. import javax.xml.parsers.SAXParserFactory;  
  179.   
  180.   
  181. import org.xml.sax.Attributes;  
  182.   
  183. import org.xml.sax.SAXException;  
  184.   
  185. import org.xml.sax.helpers.DefaultHandler;  
  186.   
  187.   
  188. public class SAXPrinter extends DefaultHandler  
  189.   
  190. {  
  191.   
  192.   
  193.   /** *//**  
  194.   
  195.    * 文檔開始事件  
  196.   
  197.    */  
  198.   
  199.     public void startDocument() throws SAXException  
  200.   
  201.     {  
  202.   
  203.         System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");  
  204.   
  205.     }  
  206.   
  207.       
  208.   
  209.   /** *//**  
  210.   
  211.    * 接收處理指令事件  
  212.   
  213.    */  
  214.   
  215.     public void processingInstruction(String target, String data) throws SAXException  
  216.   
  217.     {  
  218.   
  219.         System.out.println("<?"+target+" "+data+"?>");  
  220.   
  221.     }  
  222.   
  223.       
  224.   
  225.   /** *//**  
  226.   
  227.    * 元素開始事件  
  228.   
  229.    * 參數說明:  
  230.   
  231.    *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執行名稱空間處理,則爲空字符串。  
  232.   
  233.    *   localName - 本地名稱(不帶前綴),如果沒有正在執行名稱空間處理,則爲空字符串。  
  234.   
  235.    *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則爲空字符串。  
  236.   
  237.    *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。  
  238.   
  239.    */  
  240.   
  241.     public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException  
  242.   
  243.     {  
  244.   
  245.         System.out.print("<"+qName);//輸出元素名稱  
  246.   
  247.         int len=attrs.getLength();//元素屬性列表長度  
  248.   
  249.           
  250.   
  251.     //利用循環輸出屬性列表  
  252.   
  253.         for(int i=0;i<len;i++)  
  254.   
  255.         {  
  256.   
  257.             System.out.print(" ");  
  258.   
  259.             System.out.print(attrs.getQName(i));  
  260.   
  261.             System.out.print("=\"");  
  262.   
  263.             System.out.print(attrs.getValue(i));  
  264.   
  265.             System.out.print("\"");  
  266.   
  267.         }  
  268.   
  269.         System.out.print(">");  
  270.   
  271.     }  
  272.   
  273.       
  274.   
  275.   /** *//**  
  276.   
  277.    * 元素中字符數據事件:接收元素中字符數據  
  278.   
  279.    * 注意:1.應用程序不要試圖讀取ch數組指定範圍外的數據,(即start至length之外)  
  280.   
  281.    *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內容中的空白,而不是characters()方法,如:進行有效性驗證的解析器  
  282.   
  283.    */  
  284.   
  285.     public void characters(char[] ch, int start, int length) throws SAXException  
  286.   
  287.     {  
  288.   
  289.         System.out.print(new String(ch,start,length));  
  290.   
  291.     }  
  292.   
  293.   
  294.   /** *//**  
  295.   
  296.    * 結束元素事件  
  297.   
  298.    */  
  299.   
  300.     public void endElement(String uri, String localName, String qName) throws SAXException  
  301.   
  302.     {  
  303.   
  304.         System.out.print("</"+qName+">");  
  305.   
  306.     }  
  307.   
  308.   
  309.     public static void main(String[] args)  
  310.   
  311.     {  
  312.   
  313.         SAXParserFactory spf=SAXParserFactory.newInstance();  
  314.   
  315.           
  316.   
  317.         try  
  318.   
  319.         {  
  320.   
  321.             SAXParser sp=spf.newSAXParser();  
  322.   
  323.             sp.parse(new File("db.xml"),new SAXPrinter());  
  324.   
  325.         }  
  326.   
  327.         catch (Exception e)  
  328.   
  329.         {  
  330.   
  331.             e.printStackTrace();  
  332.   
  333.         }  
  334.   
  335.     }  
  336.   
  337. }  


 

SAX解析實例二
org.xml.sax.ContentHandler接口: 通過實現該接口給出自己的解析實現。
org.xml.sax.ErrorHandler接口:如果SAX應用程序需要實現定製的錯誤處理,那麼它必須實現這個接口,並調用XMLReader對象的setErrorHandler()方法向解析器註冊異常處理實例,這樣,解析器將通過這個接口報告所有的錯誤和警告。
ContentHandlerImpl.java

Java代碼 

  1. import org.xml.sax.Attributes;     
  2.   
  3. import org.xml.sax.ContentHandler;     
  4.   
  5. import org.xml.sax.Locator;     
  6.   
  7. import org.xml.sax.SAXException;     
  8.   
  9.     
  10.   
  11. public class ContentHandlerImpl implements ContentHandler     
  12.   
  13. {     
  14.   
  15.   /** *//**    
  16.   
  17.    * 文檔開始事件    
  18.   
  19.    */    
  20.   
  21.   public void startDocument() throws SAXException     
  22.   
  23.   {     
  24.   
  25.     System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");     
  26.   
  27.   }     
  28.   
  29.        
  30.   
  31.   /** *//**    
  32.   
  33.    * 接收處理指令事件    
  34.   
  35.    */    
  36.   
  37.   public void processingInstruction(String target, String data) throws SAXException     
  38.   
  39.   {     
  40.   
  41.     System.out.println("<?"+target+" "+data+"?>");     
  42.   
  43.   }     
  44.   
  45.        
  46.   
  47.   /** *//**    
  48.   
  49.    * 元素開始事件    
  50.   
  51.    * 參數說明:    
  52.   
  53.    *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執行名稱空間處理,則爲空字符串。    
  54.   
  55.    *   localName - 本地名稱(不帶前綴),如果沒有正在執行名稱空間處理,則爲空字符串。    
  56.   
  57.    *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則爲空字符串。    
  58.   
  59.    *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。    
  60.   
  61.    */    
  62.   
  63.   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException     
  64.   
  65.   {     
  66.   
  67.     System.out.print("<"+qName);//輸出元素名稱     
  68.   
  69.     int len=attrs.getLength();//元素屬性列表長度     
  70.   
  71.          
  72.   
  73.     //利用循環輸出屬性列表     
  74.   
  75.     for(int i=0;i<len;i++)     
  76.   
  77.     {     
  78.   
  79.       System.out.print(" ");     
  80.   
  81.       System.out.print(attrs.getQName(i));     
  82.   
  83.       System.out.print("=\"");     
  84.   
  85.       System.out.print(attrs.getValue(i));     
  86.   
  87.       System.out.print("\"");     
  88.   
  89.     }     
  90.   
  91.     System.out.print(">");     
  92.   
  93.   }     
  94.   
  95.        
  96.   
  97.   /** *//**    
  98.   
  99.    * 元素中字符數據事件:接收元素中字符數據    
  100.   
  101.    * 注意:1.應用程序不要試圖讀取ch數組指定範圍外的數據,(即start至length之外)    
  102.   
  103.    *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內容中的空白,而不是characters()方法,如:進行有效性驗證的解析器    
  104.   
  105.    */    
  106.   
  107.   public void characters(char[] ch, int start, int length) throws SAXException     
  108.   
  109.   {     
  110.   
  111.     System.out.print(new String(ch,start,length));     
  112.   
  113.   }     
  114.   
  115.     
  116.   
  117.   /** *//**    
  118.   
  119.    * 結束元素事件    
  120.   
  121.    */    
  122.   
  123.   public void endElement(String uri, String localName, String qName) throws SAXException     
  124.   
  125.   {     
  126.   
  127.     System.out.print("</"+qName+">");     
  128.   
  129.   }     
  130.   
  131.     
  132.   
  133.   public void endDocument() throws SAXException     
  134.   
  135.   {     
  136.   
  137.          
  138.   
  139.   }     
  140.   
  141.     
  142.   
  143.   public void endPrefixMapping(String prefix) throws SAXException     
  144.   
  145.   {     
  146.   
  147.          
  148.   
  149.   }     
  150.   
  151.     
  152.   
  153.   public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException     
  154.   
  155.   {     
  156.   
  157.          
  158.   
  159.   }     
  160.   
  161.     
  162.   
  163.   public void setDocumentLocator(Locator locator)     
  164.   
  165.   {     
  166.   
  167.          
  168.   
  169.   }     
  170.   
  171.     
  172.   
  173.   public void skippedEntity(String name) throws SAXException     
  174.   
  175.   {     
  176.   
  177.          
  178.   
  179.   }     
  180.   
  181.     
  182.   
  183.   public void startPrefixMapping(String prefix, String uri) throws SAXException     
  184.   
  185.   {     
  186.   
  187.          
  188.   
  189.   }     
  190.   
  191.     
  192.   
  193. }     
  194.   
  195. import org.xml.sax.Attributes;  
  196.   
  197. import org.xml.sax.ContentHandler;  
  198.   
  199. import org.xml.sax.Locator;  
  200.   
  201. import org.xml.sax.SAXException;  
  202.   
  203.   
  204. public class ContentHandlerImpl implements ContentHandler  
  205.   
  206. {  
  207.   
  208.   /** *//**  
  209.   
  210.    * 文檔開始事件  
  211.   
  212.    */  
  213.   
  214.   public void startDocument() throws SAXException  
  215.   
  216.   {  
  217.   
  218.     System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");  
  219.   
  220.   }  
  221.   
  222.     
  223.   
  224.   /** *//**  
  225.   
  226.    * 接收處理指令事件  
  227.   
  228.    */  
  229.   
  230.   public void processingInstruction(String target, String data) throws SAXException  
  231.   
  232.   {  
  233.   
  234.     System.out.println("<?"+target+" "+data+"?>");  
  235.   
  236.   }  
  237.   
  238.     
  239.   
  240.   /** *//**  
  241.   
  242.    * 元素開始事件  
  243.   
  244.    * 參數說明:  
  245.   
  246.    *   uri - 名稱空間 URI,如果元素沒有任何名稱空間 URI,或者沒有正在執行名稱空間處理,則爲空字符串。  
  247.   
  248.    *   localName - 本地名稱(不帶前綴),如果沒有正在執行名稱空間處理,則爲空字符串。  
  249.   
  250.    *   qName - 限定的名稱(帶有前綴),如果限定的名稱不可用,則爲空字符串。  
  251.   
  252.    *   attributes - 附加到元素的屬性。如果沒有屬性,則它將是空的 Attributes 對象。  
  253.   
  254.    */  
  255.   
  256.   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException  
  257.   
  258.   {  
  259.   
  260.     System.out.print("<"+qName);//輸出元素名稱  
  261.   
  262.     int len=attrs.getLength();//元素屬性列表長度  
  263.   
  264.       
  265.   
  266.     //利用循環輸出屬性列表  
  267.   
  268.     for(int i=0;i<len;i++)  
  269.   
  270.     {  
  271.   
  272.       System.out.print(" ");  
  273.   
  274.       System.out.print(attrs.getQName(i));  
  275.   
  276.       System.out.print("=\"");  
  277.   
  278.       System.out.print(attrs.getValue(i));  
  279.   
  280.       System.out.print("\"");  
  281.   
  282.     }  
  283.   
  284.     System.out.print(">");  
  285.   
  286.   }  
  287.   
  288.     
  289.   
  290.   /** *//**  
  291.   
  292.    * 元素中字符數據事件:接收元素中字符數據  
  293.   
  294.    * 注意:1.應用程序不要試圖讀取ch數組指定範圍外的數據,(即start至length之外)  
  295.   
  296.    *      2.有些解析器將使用ignorableWhitespace()方法來報告元素內容中的空白,而不是characters()方法,如:進行有效性驗證的解析器  
  297.   
  298.    */  
  299.   
  300.   public void characters(char[] ch, int start, int length) throws SAXException  
  301.   
  302.   {  
  303.   
  304.     System.out.print(new String(ch,start,length));  
  305.   
  306.   }  
  307.   
  308.   
  309.   /** *//**  
  310.   
  311.    * 結束元素事件  
  312.   
  313.    */  
  314.   
  315.   public void endElement(String uri, String localName, String qName) throws SAXException  
  316.   
  317.   {  
  318.   
  319.     System.out.print("</"+qName+">");  
  320.   
  321.   }  
  322.   
  323.   
  324.   public void endDocument() throws SAXException  
  325.   
  326.   {  
  327.   
  328.       
  329.   
  330.   }  
  331.   
  332.   
  333.   public void endPrefixMapping(String prefix) throws SAXException  
  334.   
  335.   {  
  336.   
  337.       
  338.   
  339.   }  
  340.   
  341.   
  342.   public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException  
  343.   
  344.   {  
  345.   
  346.       
  347.   
  348.   }  
  349.   
  350.   
  351.   public void setDocumentLocator(Locator locator)  
  352.   
  353.   {  
  354.   
  355.       
  356.   
  357.   }  
  358.   
  359.   
  360.   public void skippedEntity(String name) throws SAXException  
  361.   
  362.   {  
  363.   
  364.       
  365.   
  366.   }  
  367.   
  368.   
  369.   public void startPrefixMapping(String prefix, String uri) throws SAXException  
  370.   
  371.   {  
  372.   
  373.       
  374.   
  375.   }  
  376.   
  377.   
  378. }   


 

ErrorHandlerImpl.java  

Java代碼 

  1. public class ErrorHandlerImpl implements ErrorHandler     
  2.   
  3. {     
  4.   
  5.     
  6.   
  7.   public void warning(SAXParseException e) throws SAXException     
  8.   
  9.   {     
  10.   
  11.     System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());     
  12.   
  13.   }     
  14.   
  15.     
  16.   
  17.   public void error(SAXParseException e) throws SAXException     
  18.   
  19.   {     
  20.   
  21.     System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());     
  22.   
  23.   }     
  24.   
  25.     
  26.   
  27.   public void fatalError(SAXParseException e) throws SAXException     
  28.   
  29.   {     
  30.   
  31.     System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());     
  32.   
  33.   }     
  34.   
  35.     
  36.   
  37.   private String getLocationString(SAXParseException e)     
  38.   
  39.   {     
  40.   
  41.     StringBuffer sb=new StringBuffer();     
  42.   
  43.     String publicId=e.getPublicId();     
  44.   
  45.     if(publicId!=null)     
  46.   
  47.     {     
  48.   
  49.       sb.append(publicId);     
  50.   
  51.       sb.append(" ");     
  52.   
  53.     }     
  54.   
  55.          
  56.   
  57.     String systemId=e.getSystemId();     
  58.   
  59.     if(systemId!=null)     
  60.   
  61.     {     
  62.   
  63.       sb.append(systemId);     
  64.   
  65.       sb.append(" ");     
  66.   
  67.     }     
  68.   
  69.          
  70.   
  71.     sb.append(e.getLineNumber());     
  72.   
  73.     sb.append(":");     
  74.   
  75.     sb.append(e.getColumnNumber());     
  76.   
  77.     return sb.toString();     
  78.   
  79.   }     
  80.   
  81. 1. }    
  82.   
  83. public class ErrorHandlerImpl implements ErrorHandler  
  84.   
  85. {  
  86.   
  87.   
  88.   public void warning(SAXParseException e) throws SAXException  
  89.   
  90.   {  
  91.   
  92.     System.out.println("[Warning ]"+getLocationString(e)+":"+e.getMessage());  
  93.   
  94.   }  
  95.   
  96.   
  97.   public void error(SAXParseException e) throws SAXException  
  98.   
  99.   {  
  100.   
  101.     System.out.println("[Error ]"+getLocationString(e)+":"+e.getMessage());  
  102.   
  103.   }  
  104.   
  105.   
  106.   public void fatalError(SAXParseException e) throws SAXException  
  107.   
  108.   {  
  109.   
  110.     System.out.println("[Fatal Error ]"+getLocationString(e)+":"+e.getMessage());  
  111.   
  112.   }  
  113.   
  114.   
  115.   private String getLocationString(SAXParseException e)  
  116.   
  117.   {  
  118.   
  119.     StringBuffer sb=new StringBuffer();  
  120.   
  121.     String publicId=e.getPublicId();  
  122.   
  123.     if(publicId!=null)  
  124.   
  125.     {  
  126.   
  127.       sb.append(publicId);  
  128.   
  129.       sb.append(" ");  
  130.   
  131.     }  
  132.   
  133.       
  134.   
  135.     String systemId=e.getSystemId();  
  136.   
  137.     if(systemId!=null)  
  138.   
  139.     {  
  140.   
  141.       sb.append(systemId);  
  142.   
  143.       sb.append(" ");  
  144.   
  145.     }  
  146.   
  147.       
  148.   
  149.     sb.append(e.getLineNumber());  
  150.   
  151.     sb.append(":");  
  152.   
  153.     sb.append(e.getColumnNumber());  
  154.   
  155.     return sb.toString();  
  156.   
  157.   }  
  158.   
  159. }  


 

SaxParserTest.java  

Java代碼 

  1. import java.io.FileInputStream;     
  2.   
  3.     
  4.   
  5. import org.xml.sax.InputSource;     
  6.   
  7. import org.xml.sax.XMLReader;     
  8.   
  9. import org.xml.sax.helpers.XMLReaderFactory;     
  10.   
  11.     
  12.   
  13. public class SaxParserTest     
  14.   
  15. {     
  16.   
  17.   public static void main(String[] args)     
  18.   
  19.   {     
  20.   
  21.     try    
  22.   
  23.     {     
  24.   
  25.       XMLReader xmlReader=XMLReaderFactory.createXMLReader();     
  26.   
  27.       //關閉或打開驗證     
  28.   
  29.       xmlReader.setFeature("http://xml.org/sax/features/validation",true);     
  30.   
  31.       //註冊事件處理器     
  32.   
  33.       xmlReader.setContentHandler(new ContentHandlerImpl());     
  34.   
  35.       //註冊異常處理器     
  36.   
  37.       xmlReader.setErrorHandler(new ErrorHandlerImpl());     
  38.   
  39.            
  40.   
  41.       xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));     
  42.   
  43.     } catch (Exception e)     
  44.   
  45.     {     
  46.   
  47.       System.out.println(e.getMessage());     
  48.   
  49.     }     
  50.   
  51.   }     
  52.   
  53. }    
  54.   
  55. import java.io.FileInputStream;  
  56.   
  57.   
  58. import org.xml.sax.InputSource;  
  59.   
  60. import org.xml.sax.XMLReader;  
  61.   
  62. import org.xml.sax.helpers.XMLReaderFactory;  
  63.   
  64.   
  65. public class SaxParserTest  
  66.   
  67. {  
  68.   
  69.   public static void main(String[] args)  
  70.   
  71.   {  
  72.   
  73.     try  
  74.   
  75.     {  
  76.   
  77.       XMLReader xmlReader=XMLReaderFactory.createXMLReader();  
  78.   
  79.       //關閉或打開驗證  
  80.   
  81.       xmlReader.setFeature("http://xml.org/sax/features/validation",true);  
  82.   
  83.       //註冊事件處理器  
  84.   
  85.       xmlReader.setContentHandler(new ContentHandlerImpl());  
  86.   
  87.       //註冊異常處理器  
  88.   
  89.       xmlReader.setErrorHandler(new ErrorHandlerImpl());  
  90.   
  91.         
  92.   
  93.       xmlReader.parse(new InputSource(new FileInputStream("saxdb.xml")));  
  94.   
  95.     } catch (Exception e)  
  96.   
  97.     {  
  98.   
  99.       System.out.println(e.getMessage());  
  100.   
  101.     }  
  102.   
  103.   }  
  104.   
  105. }  

 

第二種:DOM解析
DOM中的核心概念就是節點。DOM在分析XML文檔時,將將組成XML文檔的各個部分(元素、屬性、文本、註釋、處理指令等)映射爲一個對象(節點)。在內存中,這些節點形成一課文檔樹。整棵樹是一個節點,樹中的每一個節點也是一棵樹(子樹),可以說,DOM就是對這棵樹的一個對象描述,我們通過訪問樹中的節點來存取XML文檔的內容。
PS:屬性節點是附屬於元素的,不能被看做是元素的子節點,更不能作爲一個單獨的節點

DOMPrinter.java

Java代碼 

  1. import org.w3c.dom.Document;     
  2.   
  3. import org.w3c.dom.NamedNodeMap;     
  4.   
  5. import org.w3c.dom.Node;     
  6.   
  7.     
  8.   
  9. import com.sun.org.apache.xerces.internal.parsers.DOMParser;     
  10.   
  11.     
  12.   
  13. public class DOMPrinter     
  14.   
  15. {     
  16.   
  17.   public static void main(String[] args)     
  18.   
  19.   {     
  20.   
  21.     try    
  22.   
  23.     {     
  24.   
  25.       /** *//** 獲取Document對象 */    
  26.   
  27.       DOMParser parser = new DOMParser();     
  28.   
  29.       parser.parse("db.xml");     
  30.   
  31.       Document document = parser.getDocument();     
  32.   
  33.       printNode(document);     
  34.   
  35.     } catch (Exception e)     
  36.   
  37.     {     
  38.   
  39.       e.printStackTrace();     
  40.   
  41.     }     
  42.   
  43.   }     
  44.   
  45.        
  46.   
  47.   public static void printNode(Node node)     
  48.   
  49.   {     
  50.   
  51.     short nodeType=node.getNodeType();     
  52.   
  53.     switch(nodeType)     
  54.   
  55.     {     
  56.   
  57.     case Node.PROCESSING_INSTRUCTION_NODE://預處理指令類型     
  58.   
  59.       printNodeInfo(node);     
  60.   
  61.       break;     
  62.   
  63.     case Node.ELEMENT_NODE://元素節點類型     
  64.   
  65.       printNodeInfo(node);     
  66.   
  67.       printAttribute(node);     
  68.   
  69.       break;     
  70.   
  71.     case Node.TEXT_NODE://文本節點類型     
  72.   
  73.       printNodeInfo(node);     
  74.   
  75.       break;     
  76.   
  77.     default:     
  78.   
  79.       break;     
  80.   
  81.     }     
  82.   
  83.          
  84.   
  85.     Node child=node.getFirstChild();     
  86.   
  87.     while(child!=null)     
  88.   
  89.     {     
  90.   
  91.       printNode(child);     
  92.   
  93.       child=child.getNextSibling();     
  94.   
  95.     }     
  96.   
  97.   }     
  98.   
  99.        
  100.   
  101.   /** *//**    
  102.   
  103.    * 根據節點類型打印節點    
  104.   
  105.    * @param node    
  106.   
  107.    */    
  108.   
  109.   public static void printNodeInfo(Node node)     
  110.   
  111.   {     
  112.   
  113.     if (node.getNodeType() == Node.ELEMENT_NODE)     
  114.   
  115.     {     
  116.   
  117.       System.out.println("NodeName: " + node.getNodeName());     
  118.   
  119.     }     
  120.   
  121.     else if (node.getNodeType() == Node.TEXT_NODE)     
  122.   
  123.     {     
  124.   
  125.       String value = node.getNodeValue().trim();     
  126.   
  127.       if (!value.equals(""))     
  128.   
  129.         System.out.println("NodeValue: " + value);     
  130.   
  131.       else    
  132.   
  133.         System.out.println();     
  134.   
  135.     }else    
  136.   
  137.     {     
  138.   
  139.       System.out.println(node.getNodeName()+" : "+node.getNodeValue());     
  140.   
  141.     }     
  142.   
  143.   }     
  144.   
  145.        
  146.   
  147.   /** *//**    
  148.   
  149.    * 打印節點屬性    
  150.   
  151.    * @param aNode 節點    
  152.   
  153.    */    
  154.   
  155.   public static void printAttribute(Node aNode)     
  156.   
  157.   {     
  158.   
  159.     NamedNodeMap attrs = aNode.getAttributes();     
  160.   
  161.     if(attrs!=null)     
  162.   
  163.     {     
  164.   
  165.       for (int i = 0; i < attrs.getLength(); i++)     
  166.   
  167.       {     
  168.   
  169.         Node attNode = attrs.item(i);     
  170.   
  171.         System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");     
  172.   
  173.       }     
  174.   
  175.     }     
  176.   
  177.   }    
  178.   
  179. import org.w3c.dom.Document;  
  180.   
  181. import org.w3c.dom.NamedNodeMap;  
  182.   
  183. import org.w3c.dom.Node;  
  184.   
  185.   
  186. import com.sun.org.apache.xerces.internal.parsers.DOMParser;  
  187.   
  188.   
  189. public class DOMPrinter  
  190.   
  191. {  
  192.   
  193.   public static void main(String[] args)  
  194.   
  195.   {  
  196.   
  197.     try  
  198.   
  199.     {  
  200.   
  201.       /** *//** 獲取Document對象 */  
  202.   
  203.       DOMParser parser = new DOMParser();  
  204.   
  205.       parser.parse("db.xml");  
  206.   
  207.       Document document = parser.getDocument();  
  208.   
  209.       printNode(document);  
  210.   
  211.     } catch (Exception e)  
  212.   
  213.     {  
  214.   
  215.       e.printStackTrace();  
  216.   
  217.     }  
  218.   
  219.   }  
  220.   
  221.     
  222.   
  223.   public static void printNode(Node node)  
  224.   
  225.   {  
  226.   
  227.     short nodeType=node.getNodeType();  
  228.   
  229.     switch(nodeType)  
  230.   
  231.     {  
  232.   
  233.     case Node.PROCESSING_INSTRUCTION_NODE://預處理指令類型  
  234.   
  235.       printNodeInfo(node);  
  236.   
  237.       break;  
  238.   
  239.     case Node.ELEMENT_NODE://元素節點類型  
  240.   
  241.       printNodeInfo(node);  
  242.   
  243.       printAttribute(node);  
  244.   
  245.       break;  
  246.   
  247.     case Node.TEXT_NODE://文本節點類型  
  248.   
  249.       printNodeInfo(node);  
  250.   
  251.       break;  
  252.   
  253.     default:  
  254.   
  255.       break;  
  256.   
  257.     }  
  258.   
  259.       
  260.   
  261.     Node child=node.getFirstChild();  
  262.   
  263.     while(child!=null)  
  264.   
  265.     {  
  266.   
  267.       printNode(child);  
  268.   
  269.       child=child.getNextSibling();  
  270.   
  271.     }  
  272.   
  273.   }  
  274.   
  275.     
  276.   
  277.   /** *//**  
  278.   
  279.    * 根據節點類型打印節點  
  280.   
  281.    * @param node  
  282.   
  283.    */  
  284.   
  285.   public static void printNodeInfo(Node node)  
  286.   
  287.   {  
  288.   
  289.     if (node.getNodeType() == Node.ELEMENT_NODE)  
  290.   
  291.     {  
  292.   
  293.       System.out.println("NodeName: " + node.getNodeName());  
  294.   
  295.     }  
  296.   
  297.     else if (node.getNodeType() == Node.TEXT_NODE)  
  298.   
  299.     {  
  300.   
  301.       String value = node.getNodeValue().trim();  
  302.   
  303.       if (!value.equals(""))  
  304.   
  305.         System.out.println("NodeValue: " + value);  
  306.   
  307.       else  
  308.   
  309.         System.out.println();  
  310.   
  311.     }else  
  312.   
  313.     {  
  314.   
  315.       System.out.println(node.getNodeName()+" : "+node.getNodeValue());  
  316.   
  317.     }  
  318.   
  319.   }  
  320.   
  321.     
  322.   
  323.   /** *//**  
  324.   
  325.    * 打印節點屬性  
  326.   
  327.    * @param aNode 節點  
  328.   
  329.    */  
  330.   
  331.   public static void printAttribute(Node aNode)  
  332.   
  333.   {  
  334.   
  335.     NamedNodeMap attrs = aNode.getAttributes();  
  336.   
  337.     if(attrs!=null)  
  338.   
  339.     {  
  340.   
  341.       for (int i = 0; i < attrs.getLength(); i++)  
  342.   
  343.       {  
  344.   
  345.         Node attNode = attrs.item(i);  
  346.   
  347.         System.out.println("Attribute: " + attNode.getNodeName() + "=\"" + attNode.getNodeValue()+"\"");  
  348.   
  349.       }  
  350.   
  351.     }  
  352.   
  353.   }  

 

DOM生成XML文檔:DOMCreateExample.java  

Java代碼 

  1. import java.io.FileNotFoundException;     
  2.   
  3. import java.io.FileOutputStream;     
  4.   
  5. import java.io.IOException;     
  6.   
  7.     
  8.   
  9. import javax.xml.parsers.DocumentBuilder;     
  10.   
  11. import javax.xml.parsers.DocumentBuilderFactory;     
  12.   
  13. import javax.xml.parsers.ParserConfigurationException;     
  14.   
  15.     
  16.   
  17. import org.w3c.dom.Document;     
  18.   
  19. import org.w3c.dom.Element;     
  20.   
  21.     
  22.   
  23. import com.sun.org.apache.xml.internal.serialize.XMLSerializer;     
  24.   
  25.     
  26.   
  27. public class DOMCreateExample     
  28.   
  29. {     
  30.   
  31.   public static void main(String[] args) throws ParserConfigurationException     
  32.   
  33.   {     
  34.   
  35.     //DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation();     
  36.   
  37.     DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance();     
  38.   
  39.     DocumentBuilder builder = builderFact.newDocumentBuilder();     
  40.   
  41.         
  42.   
  43.     Document doc = builder.newDocument();     
  44.   
  45.     //Document doc = domImp.createDocument(null, null, null);     
  46.   
  47.         
  48.   
  49.     Element root = doc.createElement("games");     
  50.   
  51.     Element child1 = doc.createElement("game");     
  52.   
  53.     child1.appendChild(doc.createTextNode("Final Fantasy VII"));     
  54.   
  55.     child1.setAttribute("genre", "rpg");     
  56.   
  57.     root.appendChild(child1);     
  58.   
  59.     doc.appendChild(root);     
  60.   
  61.           
  62.   
  63.      XMLSerializer serial;     
  64.   
  65.     try    
  66.   
  67.     {     
  68.   
  69.       serial = new XMLSerializer(new FileOutputStream("domcreate.xml"), null);     
  70.   
  71.       serial.serialize(doc);     
  72.   
  73.     } catch (FileNotFoundException e1)     
  74.   
  75.     {     
  76.   
  77.       e1.printStackTrace();     
  78.   
  79.     } catch (IOException e)     
  80.   
  81.     {     
  82.   
  83.       e.printStackTrace();     
  84.   
  85.     }     
  86.   
  87.   }     
  88.   
  89. }    
  90.   
  91. import java.io.FileNotFoundException;  
  92.   
  93. import java.io.FileOutputStream;  
  94.   
  95. import java.io.IOException;  
  96.   
  97.   
  98. import javax.xml.parsers.DocumentBuilder;  
  99.   
  100. import javax.xml.parsers.DocumentBuilderFactory;  
  101.   
  102. import javax.xml.parsers.ParserConfigurationException;  
  103.   
  104.   
  105. import org.w3c.dom.Document;  
  106.   
  107. import org.w3c.dom.Element;  
  108.   
  109.   
  110. import com.sun.org.apache.xml.internal.serialize.XMLSerializer;  
  111.   
  112.   
  113. public class DOMCreateExample  
  114.   
  115. {  
  116.   
  117.   public static void main(String[] args) throws ParserConfigurationException  
  118.   
  119.   {  
  120.   
  121.     //DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation();  
  122.   
  123.     DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance();  
  124.   
  125.     DocumentBuilder builder = builderFact.newDocumentBuilder();  
  126.   
  127.      
  128.   
  129.     Document doc = builder.newDocument();  
  130.   
  131.     //Document doc = domImp.createDocument(null, null, null);  
  132.   
  133.      
  134.   
  135.     Element root = doc.createElement("games");  
  136.   
  137.     Element child1 = doc.createElement("game");  
  138.   
  139.     child1.appendChild(doc.createTextNode("Final Fantasy VII"));  
  140.   
  141.     child1.setAttribute("genre", "rpg");  
  142.   
  143.     root.appendChild(child1);  
  144.   
  145.     doc.appendChild(root);  
  146.   
  147.        
  148.   
  149.      XMLSerializer serial;  
  150.   
  151.     try  
  152.   
  153.     {  
  154.   
  155.       serial = new XMLSerializer(new FileOutputStream("domcreate.xml"), null);  
  156.   
  157.       serial.serialize(doc);  
  158.   
  159.     } catch (FileNotFoundException e1)  
  160.   
  161.     {  
  162.   
  163.       e1.printStackTrace();  
  164.   
  165.     } catch (IOException e)  
  166.   
  167.     {  
  168.   
  169.       e.printStackTrace();  
  170.   
  171.     }  
  172.   
  173.   }  
  174.   
  175. }  

 

第三種JDOM解析 
JDOM利用了java語言的優秀特性,極大地簡化了對XML文檔的處理,相比DOM簡單易用。JDOM也使用對象樹來表示XML文檔,JDOM使用SAXj解析器來分析XML文檔,構建JDOM樹。然而JOMD本身並沒有提供解析器,它使用其他開發商提供的標準SAX解析器,JDOM默認通過JAXP來選擇解析器,可以通過手動知道解析器的類名來設置。
首先要在工程中添加jdom的jar包,這裏使用jdom1.0.jar。(見附件)
JDOMConvert.java 

Java代碼 

  1. import java.io.File;     
  2.   
  3.     
  4.   
  5. import org.jdom.Document;     
  6.   
  7. import org.jdom.Element;     
  8.   
  9. import org.jdom.input.SAXBuilder;     
  10.   
  11. import org.jdom.output.Format;     
  12.   
  13. import org.jdom.output.XMLOutputter;     
  14.   
  15.     
  16.   
  17. public class JDOMConvert     
  18.   
  19. {     
  20.   
  21.     public static void main(String[] args)     
  22.   
  23.     {     
  24.   
  25.         SAXBuilder saxBuilder=new SAXBuilder();     
  26.   
  27.         try    
  28.   
  29.         {     
  30.   
  31.             Document doc=saxBuilder.build(new File("domdb.xml"));     
  32.   
  33.            
  34.   
  35.       //首先創建好節點     
  36.   
  37.       Element eltDb=new Element("db");     
  38.   
  39.       Element eltDriver=new Element("driver");     
  40.   
  41.       Element eltUrl=new Element("url");     
  42.   
  43.       Element eltUser=new Element("user");     
  44.   
  45.       Element eltPassword=new Element("password");     
  46.   
  47.            
  48.   
  49.       //設置節點的值     
  50.   
  51.       eltDriver.setText("com.mysql.jdbc.Driver");     
  52.   
  53.       eltUrl.setText("jdbc:mysql://localhost/mySql");     
  54.   
  55.       eltUser.setText("root");     
  56.   
  57.       eltPassword.setText("xlc");     
  58.   
  59.            
  60.   
  61.       //添加到根節點     
  62.   
  63.       eltDb.addContent(eltDriver);     
  64.   
  65.       eltDb.addContent(eltUrl);     
  66.   
  67.       eltDb.addContent(eltUser);     
  68.   
  69.       eltDb.addContent(eltPassword);     
  70.   
  71.       //根節點設置屬性     
  72.   
  73.       eltDb.setAttribute("type","mysql");     
  74.   
  75.            
  76.   
  77.       Element root=doc.getRootElement();     
  78.   
  79.       //root.removeChild("db");//刪除節點     
  80.   
  81.       root.addContent(eltDb);//增加節點     
  82.   
  83.            
  84.   
  85.       //修改db節點中內容     
  86.   
  87.       root.getChild("db").getChild("user").setText("system");     
  88.   
  89.       root.getChild("db").getChild("password").setText("manager");     
  90.   
  91.            
  92.   
  93.             XMLOutputter xmlOut=new XMLOutputter();     
  94.   
  95.                  
  96.   
  97.       //設置XML格式     
  98.   
  99.             Format fmt=Format.getPrettyFormat();     
  100.   
  101.             fmt.setIndent("    ");     
  102.   
  103.             fmt.setEncoding("utf-8");     
  104.   
  105.                  
  106.   
  107.             xmlOut.setFormat(fmt);     
  108.   
  109.             xmlOut.output(doc,System.out);     
  110.   
  111.         }     
  112.   
  113.         catch (Exception e)     
  114.   
  115.         {     
  116.   
  117.             e.printStackTrace();     
  118.   
  119.         }     
  120.   
  121.     }     
  122.   
  123. }    
  124.   
  125. import java.io.File;  
  126.   
  127.   
  128. import org.jdom.Document;  
  129.   
  130. import org.jdom.Element;  
  131.   
  132. import org.jdom.input.SAXBuilder;  
  133.   
  134. import org.jdom.output.Format;  
  135.   
  136. import org.jdom.output.XMLOutputter;  
  137.   
  138.   
  139. public class JDOMConvert  
  140.   
  141. {  
  142.   
  143.     public static void main(String[] args)  
  144.   
  145.     {  
  146.   
  147.         SAXBuilder saxBuilder=new SAXBuilder();  
  148.   
  149.         try  
  150.   
  151.         {  
  152.   
  153.             Document doc=saxBuilder.build(new File("domdb.xml"));  
  154.   
  155.         
  156.   
  157.       //首先創建好節點  
  158.   
  159.       Element eltDb=new Element("db");  
  160.   
  161.       Element eltDriver=new Element("driver");  
  162.   
  163.       Element eltUrl=new Element("url");  
  164.   
  165.       Element eltUser=new Element("user");  
  166.   
  167.       Element eltPassword=new Element("password");  
  168.   
  169.         
  170.   
  171.       //設置節點的值  
  172.   
  173.       eltDriver.setText("com.mysql.jdbc.Driver");  
  174.   
  175.       eltUrl.setText("jdbc:mysql://localhost/mySql");  
  176.   
  177.       eltUser.setText("root");  
  178.   
  179.       eltPassword.setText("xlc");  
  180.   
  181.         
  182.   
  183.       //添加到根節點  
  184.   
  185.       eltDb.addContent(eltDriver);  
  186.   
  187.       eltDb.addContent(eltUrl);  
  188.   
  189.       eltDb.addContent(eltUser);  
  190.   
  191.       eltDb.addContent(eltPassword);  
  192.   
  193.       //根節點設置屬性  
  194.   
  195.       eltDb.setAttribute("type","mysql");  
  196.   
  197.         
  198.   
  199.       Element root=doc.getRootElement();  
  200.   
  201.       //root.removeChild("db");//刪除節點  
  202.   
  203.       root.addContent(eltDb);//增加節點  
  204.   
  205.         
  206.   
  207.       //修改db節點中內容  
  208.   
  209.       root.getChild("db").getChild("user").setText("system");  
  210.   
  211.       root.getChild("db").getChild("password").setText("manager");  
  212.   
  213.         
  214.   
  215.             XMLOutputter xmlOut=new XMLOutputter();  
  216.   
  217.               
  218.   
  219.       //設置XML格式  
  220.   
  221.             Format fmt=Format.getPrettyFormat();  
  222.   
  223.             fmt.setIndent("    ");  
  224.   
  225.             fmt.setEncoding("utf-8");  
  226.   
  227.               
  228.   
  229.             xmlOut.setFormat(fmt);  
  230.   
  231.             xmlOut.output(doc,System.out);  
  232.   
  233.         }  
  234.   
  235.         catch (Exception e)  
  236.   
  237.         {  
  238.   
  239.             e.printStackTrace();  
  240.   
  241.         }  
  242.   
  243.     }  
  244.   
  245. }  


JDOM生成XML文檔:JDOMCreate.java  

Java代碼 

  1. <span style="color:#000000;">import java.io.IOException;     
  2.   
  3.     
  4.   
  5. import org.jdom.Document;     
  6.   
  7. import org.jdom.Element;     
  8.   
  9. import org.jdom.output.XMLOutputter;     
  10.   
  11.     
  12.   
  13. public class JDOMCreate     
  14.   
  15. {     
  16.   
  17.   public static void main(String[] args)     
  18.   
  19.   {     
  20.   
  21.     Document doc = new Document(new Element("games"));     
  22.   
  23.     Element newGame = new Element("game").setText("Final Fantasy VI");     
  24.   
  25.     doc.getRootElement().addContent(newGame);     
  26.   
  27.     newGame.setAttribute("genre""rpg");     
  28.   
  29.     XMLOutputter domstream = new XMLOutputter();     
  30.   
  31.     try    
  32.   
  33.     {     
  34.   
  35.       domstream.output(doc, System.out);     
  36.   
  37.     } catch (IOException e)     
  38.   
  39.     {     
  40.   
  41.       e.printStackTrace();     
  42.   
  43.     }     
  44.   
  45.   }     
  46.   
  47. }    
  48.   
  49. import java.io.IOException;  
  50.   
  51.   
  52. import org.jdom.Document;  
  53.   
  54. import org.jdom.Element;  
  55.   
  56. import org.jdom.output.XMLOutputter;  
  57.   
  58.   
  59. public class JDOMCreate  
  60.   
  61. {  
  62.   
  63.   public static void main(String[] args)  
  64.   
  65.   {  
  66.   
  67.     Document doc = new Document(new Element("games"));  
  68.   
  69.     Element newGame = new Element("game").setText("Final Fantasy VI");  
  70.   
  71.     doc.getRootElement().addContent(newGame);  
  72.   
  73.     newGame.setAttribute("genre""rpg");  
  74.   
  75.     XMLOutputter domstream = new XMLOutputter();  
  76.   
  77.     try  
  78.   
  79.     {  
  80.   
  81.       domstream.output(doc, System.out);  
  82.   
  83.     } catch (IOException e)  
  84.   
  85.     {  
  86.   
  87.       e.printStackTrace();  
  88.   
  89.     }  
  90.   
  91.   }  
  92.   
  93. }  
  94.   
  95. </span>  

第四種:DOM4J解析
dom4j與JDOM一樣,也是一種用於解析XML文檔的開放源代碼的XML框架,dom4j也應用於java平臺,dom4j API使用了java集合框架並完全支持DOM、SAX和JAXP。與JDOM不同的是,dom4j使用接口和抽象類,雖然dom4j的API相對複雜些,但它提供了比JDOM更好的靈活性。dom4j也使用SAX解析器來分析XML文檔,創建dom4j樹。此外dom4j也可以接收DOM格式的內容,並提供了從dom4j樹到SAX事件流或W3C DOM樹的輸出機制。與JDOM不同,dom4j自帶了一個SAX解析器Aelfred2,如果沒有顯示的設置SAX解析器,也沒有通過系統屬性org.xml.sax.driver設置解析器,dom3j將會使用JAXP來加載JAXP配置的解析器,如果創建解析器失敗,那麼最後才使用dom4j自帶的Aelfred2解析器。
同樣,首先要在工程中添加dom4j的jar包,這裏使用dom4j-1.6.1.jar。(見附件)
Dom4j生成XML文檔db.xml:Dom4jCreate.java 

Java代碼 

  1. import java.io.IOException;     
  2.   
  3.     
  4.   
  5. import org.dom4j.Document;     
  6.   
  7. import org.dom4j.DocumentHelper;     
  8.   
  9. import org.dom4j.Element;     
  10.   
  11. import org.dom4j.io.OutputFormat;     
  12.   
  13. import org.dom4j.io.XMLWriter;     
  14.   
  15.     
  16.   
  17. public class Dom4jCreate     
  18.   
  19. {     
  20.   
  21.     
  22.   
  23.   public static void main(String[] args)     
  24.   
  25.   {     
  26.   
  27.     Document doc = DocumentHelper.createDocument();     
  28.   
  29.     
  30.   
  31.     doc.addProcessingInstruction("xml-stylesheet""type='text/xsl' href='db.xsl'");     
  32.   
  33.     doc.addDocType("dbconfig"null,"db.dtd");     
  34.   
  35.          
  36.   
  37.     //Element root=DocumentHelper.createElement("dbconfig");     
  38.   
  39.     // doc.setRootElement(root);     
  40.   
  41.     Element root = doc.addElement("dbconfig");     
  42.   
  43.     
  44.   
  45.     Element eltDb= root.addElement("db");     
  46.   
  47.     Element eltDriver = eltDb.addElement("driver");     
  48.   
  49.     Element eltUrl = eltDb.addElement("url");     
  50.   
  51.     Element eltUser = eltDb.addElement("user");     
  52.   
  53.     Element eltPassword = eltDb.addElement("password");     
  54.   
  55.          
  56.   
  57.     eltDriver.setText("com.mysql.jdbc.Driver");     
  58.   
  59.     eltUrl.setText("jdbc:mysql://localhost/mySql");     
  60.   
  61.     eltUser.setText("root");     
  62.   
  63.     eltPassword.setText("xlc");     
  64.   
  65.     eltDb.addAttribute("type","mysql");     
  66.   
  67.              
  68.   
  69.     try    
  70.   
  71.     {     
  72.   
  73.       //設置輸出格式     
  74.   
  75.       OutputFormat outFmt = new OutputFormat("    "true);     
  76.   
  77.       outFmt.setEncoding("UTF-8");     
  78.   
  79.            
  80.   
  81.       /**//*PrintWriter pw = new PrintWriter(System.out);   
  82.  
  83.       doc.write(pw);   
  84.  
  85.       pw.flush();   
  86.  
  87.       pw.close();*/    
  88.   
  89.     
  90.   
  91.       XMLWriter xmlWriter = new XMLWriter(System.out, outFmt);     
  92.   
  93.       // XMLWriter xmlWriter=new XMLWriter(new FileWriter("db.xml"),outFmt);     
  94.   
  95.       xmlWriter.write(doc);     
  96.   
  97.       xmlWriter.flush();     
  98.   
  99.       xmlWriter.close();     
  100.   
  101.     } catch (IOException e)     
  102.   
  103.     {     
  104.   
  105.       e.printStackTrace();     
  106.   
  107.     }     
  108.   
  109.   }     
  110.   
  111. }    
  112.   
  113. import java.io.IOException;  
  114.   
  115.   
  116. import org.dom4j.Document;  
  117.   
  118. import org.dom4j.DocumentHelper;  
  119.   
  120. import org.dom4j.Element;  
  121.   
  122. import org.dom4j.io.OutputFormat;  
  123.   
  124. import org.dom4j.io.XMLWriter;  
  125.   
  126.   
  127. public class Dom4jCreate  
  128.   
  129. {  
  130.   
  131.   
  132.   public static void main(String[] args)  
  133.   
  134.   {  
  135.   
  136.     Document doc = DocumentHelper.createDocument();  
  137.   
  138.   
  139.     doc.addProcessingInstruction("xml-stylesheet""type='text/xsl' href='db.xsl'");  
  140.   
  141.     doc.addDocType("dbconfig"null,"db.dtd");  
  142.   
  143.       
  144.   
  145.     //Element root=DocumentHelper.createElement("dbconfig");  
  146.   
  147.     // doc.setRootElement(root);  
  148.   
  149.     Element root = doc.addElement("dbconfig");  
  150.   
  151.   
  152.     Element eltDb= root.addElement("db");  
  153.   
  154.     Element eltDriver = eltDb.addElement("driver");  
  155.   
  156.     Element eltUrl = eltDb.addElement("url");  
  157.   
  158.     Element eltUser = eltDb.addElement("user");  
  159.   
  160.     Element eltPassword = eltDb.addElement("password");  
  161.   
  162.       
  163.   
  164.     eltDriver.setText("com.mysql.jdbc.Driver");  
  165.   
  166.     eltUrl.setText("jdbc:mysql://localhost/mySql");  
  167.   
  168.     eltUser.setText("root");  
  169.   
  170.     eltPassword.setText("xlc");  
  171.   
  172.     eltDb.addAttribute("type","mysql");  
  173.   
  174.           
  175.   
  176.     try  
  177.   
  178.     {  
  179.   
  180.       //設置輸出格式  
  181.   
  182.       OutputFormat outFmt = new OutputFormat("    "true);  
  183.   
  184.       outFmt.setEncoding("UTF-8");  
  185.   
  186.         
  187.   
  188.       /**//*PrintWriter pw = new PrintWriter(System.out); 
  189.  
  190.       doc.write(pw); 
  191.  
  192.       pw.flush(); 
  193.  
  194.       pw.close();*/  
  195.   
  196.   
  197.       XMLWriter xmlWriter = new XMLWriter(System.out, outFmt);  
  198.   
  199.       // XMLWriter xmlWriter=new XMLWriter(new FileWriter("db.xml"),outFmt);  
  200.   
  201.       xmlWriter.write(doc);  
  202.   
  203.       xmlWriter.flush();  
  204.   
  205.       xmlWriter.close();  
  206.   
  207.     } catch (IOException e)  
  208.   
  209.     {  
  210.   
  211.       e.printStackTrace();  
  212.   
  213.     }  
  214.   
  215.   }  
  216.   
  217. }  


 

Dom4j修改XML文檔db.xml:Dom4jModify.java 

Java代碼 

  1. import java.io.File;     
  2.   
  3. import java.io.FileWriter;     
  4.   
  5. import java.util.Iterator;     
  6.   
  7. import java.util.List;     
  8.   
  9.     
  10.   
  11. import org.dom4j.Document;     
  12.   
  13. import org.dom4j.Element;     
  14.   
  15. import org.dom4j.io.OutputFormat;     
  16.   
  17. import org.dom4j.io.SAXReader;     
  18.   
  19. import org.dom4j.io.XMLWriter;     
  20.   
  21.     
  22.   
  23. public class Dom4jModify     
  24.   
  25. {     
  26.   
  27.   public Document modifyDocument(File inputXml)     
  28.   
  29.   {     
  30.   
  31.     try    
  32.   
  33.     {     
  34.   
  35.       SAXReader saxReader = new SAXReader();     
  36.   
  37.       Document document = saxReader.read(inputXml);     
  38.   
  39.       document.addDocType("dbconfig",null,"db.dtd");     
  40.   
  41.       List list = document.content();     
  42.   
  43.     
  44.   
  45.       // Iterator iter = document.nodeIterator();     
  46.   
  47.       Iterator iter = list.iterator();     
  48.   
  49.     
  50.   
  51.       Element element = (Element) iter.next();     
  52.   
  53.       element.element("db").attribute("type").setValue("mysql");     
  54.   
  55.       element.element("db").element("url").setText("jdbc:mysql://localhost/mySql");     
  56.   
  57.       element.element("db").element("driver").setText("com.mysql.jdbc.Driver");     
  58.   
  59.       element.element("db").element("user").setText("root");     
  60.   
  61.       element.element("db").element("password").setText("xlc");     
  62.   
  63.            
  64.   
  65.       // 設置輸出格式     
  66.   
  67.       OutputFormat outFmt = new OutputFormat("    ", true);     
  68.   
  69.       outFmt.setEncoding("UTF-8");     
  70.   
  71.            
  72.   
  73.       XMLWriter xmlWriter=new XMLWriter(new FileWriter("domdb-modified.xml"),outFmt);     
  74.   
  75.       xmlWriter.write(document);     
  76.   
  77.       xmlWriter.flush();     
  78.   
  79.       xmlWriter.close();     
  80.   
  81.       return document;     
  82.   
  83.     }     
  84.   
  85.     catch (Exception e)     
  86.   
  87.     {     
  88.   
  89.       System.out.println(e.getMessage());     
  90.   
  91.       return null;     
  92.   
  93.     }     
  94.   
  95.   }     
  96.   
  97.     
  98.   
  99.   public static void main(String[] args) throws Exception     
  100.   
  101.   {     
  102.   
  103.     Dom4jModify dom4jParser = new Dom4jModify();     
  104.   
  105.     Document document = dom4jParser.modifyDocument(new File("domdb.xml"));     
  106.   
  107.          
  108.   
  109.     OutputFormat outFmt = new OutputFormat("    ", true);     
  110.   
  111.     outFmt.setEncoding("UTF-8");     
  112.   
  113.     XMLWriter xmlWriter = new XMLWriter(System.out,outFmt);     
  114.   
  115.     xmlWriter.write(document);     
  116.   
  117. xmlWriter.flush();     
  118.   
  119. xmlWriter.close();     
  120.   
  121. }     
  122.   
  123. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章