一路拾遺
          Collect By Finding All The Way ......
          posts - 81,comments - 41,trackbacks - 0
          這是自己整理的xml解析,參考了網上的例子:
          Xml代碼 復制代碼
          1. <?xml version="1.0" encoding="UTF-8"?>  
          2. <catalog>  
          3.     <!--An XML Catalog-->  
          4.     <books title="XML Zone" publisher="IBM developerWorks">  
          5.         <book level="Intermediate" date="December-2001">  
          6.             <title>Java OO Book</title>  
          7.             <author>author</author>  
          8.         </book>  
          9.     </books>  
          10. </catalog>  

          1、jdom解析
          Java代碼 復制代碼
          1. package cn.xml;   
          2. import java.io.FileNotFoundException;   
          3. import java.io.FileOutputStream;   
          4. import java.io.IOException;   
          5. import java.util.Iterator;   
          6. import java.util.List;   
          7.   
          8. import org.jdom.Document;   
          9. import org.jdom.Element;   
          10. import org.jdom.JDOMException;   
          11. import org.jdom.input.SAXBuilder;   
          12. import org.jdom.output.XMLOutputter;   
          13.   
          14. /**  
          15.  * yicha   
          16.  * Dec 2, 2008 JDom解析  
          17.  */  
          18.   
          19. public class JDomParse  {   
          20.   
          21.     /**  
          22.      * @param args  
          23.      * @throws IOException   
          24.      * @throws FileNotFoundException   
          25.      * @throws JDOMException   
          26.      */  
          27.     public static void main(String[] args) throws FileNotFoundException, IOException, JDOMException {   
          28.         String xmlpath="c:/catalog.xml";   
          29.         //使用JDOM首先要指定使用什么解析器   
          30.         SAXBuilder builder=new SAXBuilder(false);//這表示使用的是默認的解析器   
          31.         //得到Document,以后要進行的所有操作都是對這個Document操作的   
          32.         Document doc=builder.build(xmlpath);   
          33.         //得到根元素   
          34.         Element root=doc.getRootElement();   
          35.         //得到元素(節點)的集合   
          36.         List bookslist=root.getChildren("books");   
          37.         //輪循List集合   
          38.         for (Iterator iter = bookslist.iterator(); iter.hasNext();) {   
          39.              Element books= (Element) iter.next();   
          40.              List bookList=books.getChildren("book");   
          41.              for(Iterator it=bookList.iterator();it.hasNext();){   
          42.                  Element book= (Element) it.next();   
          43.                  //取得元素的屬性   
          44.                  String level=book.getAttributeValue("level");   
          45.                  System.out.println(level);   
          46.                  //取得元素的子元素(為最低層元素)的值  注意的是,必須確定book元素的名為“name”的子元素只有一個。   
          47.                  String author=book.getChildTextTrim("author");   
          48.                  System.out.println(author);                
          49.                  //改變元素(為最低層元素)的值;對Document的修改,并沒有在實際的XML文檔中進行修改   
          50.                  book.getChild("author").setText("author_test");   
          51.              }   
          52.                 
          53.         }   
          54.         //保存Document的修改到XML文件中   
          55. //      XMLOutputter outputter=new XMLOutputter();   
          56. //      outputter.output(doc,new FileOutputStream(xmlpath));   
          57.   
          58.     }   
          59.   
          60. }  


          dom解析:
          Java代碼 復制代碼
          1. package cn.xml;   
          2.   
          3. import java.io.File;   
          4.   
          5. import javax.xml.parsers.DocumentBuilder;   
          6. import javax.xml.parsers.DocumentBuilderFactory;   
          7.   
          8. import org.w3c.dom.Document;   
          9. import org.w3c.dom.NodeList;   
          10.   
          11. /**  
          12.  * yicha   
          13.  * Dec 1, 2008  
          14.  * DOM解析   
          15.  */  
          16.   
          17. public class DomPhase {   
          18.   
          19.     /**  
          20.      * @param args  
          21.      */  
          22.     public static void main(String[] args) {   
          23.         long lasting =System.currentTimeMillis();   
          24.         try{   
          25.             File f=new File("c:/catalog.xml");   
          26.             DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();   
          27.             DocumentBuilder builder=factory.newDocumentBuilder();   
          28.             Document doc = builder.parse(f);   
          29.             NodeList nl = doc.getElementsByTagName("author");   
          30.             for (int i=0;i<nl.getLength();i++){   
          31.                 System.out.println("firstname:" + doc.getElementsByTagName("firstname").item(i).getFirstChild().getNodeValue());   
          32.                 System.out.println(" lastname:" + doc.getElementsByTagName("lastname").item(i).getFirstChild().getNodeValue());   
          33.             }   
          34.         }catch(Exception e){   
          35.                 e.printStackTrace();   
          36.         }   
          37.         System.out.println("運行時間:"+(System.currentTimeMillis() - lasting)+" 毫秒");   
          38.     }    
          39. }  

          dom4j解析:
          Java代碼 復制代碼
          1. package cn.xml;   
          2.   
          3. import java.io.File;   
          4. import java.io.FileOutputStream;   
          5. import java.io.IOException;   
          6. import java.util.HashMap;   
          7. import java.util.Iterator;   
          8. import java.util.List;   
          9.   
          10. import org.dom4j.Attribute;   
          11. import org.dom4j.Document;   
          12. import org.dom4j.DocumentException;   
          13. import org.dom4j.DocumentHelper;   
          14. import org.dom4j.Element;   
          15. import org.dom4j.io.OutputFormat;   
          16. import org.dom4j.io.SAXReader;   
          17. import org.dom4j.io.XMLWriter;   
          18.   
          19. /**  
          20.  * yicha   
          21.  * Dec 1, 2008   
          22.  */  
          23.   
          24. public class Dom4JPhase {   
          25.        
          26.     /**  
          27.      * 產生xml文檔  
          28.      */  
          29.     public void generateDocument(){    
          30.           //使用 DocumentHelper 類創建一個文檔實例。 DocumentHelper 是生成 XML 文檔節點的 dom4j API 工廠類      
          31.            Document document = DocumentHelper.createDocument();                  
          32.            //使用 addElement()方法創建根元素catalog , addElement()用于向 XML 文檔中增加元素      
          33.            Element catalogElement = document.addElement("catalog");   
          34.            //在 catalog 元素中使用 addComment() 方法添加注釋"An XML catalog"      
          35.            catalogElement.addComment("An XML Catalog");    
          36.            //在 catalog 元素中使用 addProcessingInstruction() 方法增加一個處理指令 (不知有什么用)     
          37. //         catalogElement.addProcessingInstruction("target","text");   
          38.            //在 catalog 元素中使用 addElement() 方法增加 journal 節點      
          39.            Element booksElement = catalogElement.addElement("books");      
          40.            //使用 addAttribute() 方法向 book節點添加 title 和 publisher 屬性      
          41.            booksElement.addAttribute("title""XML Zone");      
          42.            booksElement.addAttribute("publisher""IBM developerWorks");              
          43.            //添加子節點   
          44.            Element bookElement=booksElement.addElement("book");      
          45.            //添加屬性      
          46.            bookElement.addAttribute("level""Intermediate");      
          47.            bookElement.addAttribute("date""December-2001");    
          48.            //添加節點   
          49.            Element titleElement=bookElement.addElement("title");     
          50.            //添加內容   
          51.            titleElement.setText("Java OO Book");     
          52.            //添加節點   
          53.            Element authorElement=bookElement.addElement("author");     
          54.            //添加節點   
          55.            authorElement.setText("author");                          
          56.            //可以使用 addDocType() 方法添加文檔類型說明      
          57.            //這樣就向 XML 文檔中增加文檔類型說明:      
          58. //         document.addDocType("catalog","nikee","file://c:/Dtds/catalog.dtd");      
          59.            try{       
          60.                FileOutputStream fos=new FileOutputStream("c:/catalog.xml");      
          61.                OutputFormat of=new OutputFormat("    "true);      
          62.                XMLWriter xw=new XMLWriter(fos, of);      
          63.                xw.write( document );      
          64.                xw.close();      
          65.            } catch(IOException e)    {      
          66.             System.out.println(e.getMessage());      
          67.            }      
          68.       }      
          69.          
          70.     /**  
          71.      * 讀取xml文件的元素值  
          72.      * @param list  
          73.      */  
          74.     public void getXMLValue(List list){   
          75. //      List list=element.elements();   
          76.         if(list==null||list.size()==0){   
          77.             return;   
          78.         }   
          79.         for(int i=0;i<list.size();i++){   
          80.              Element foo = (Element) list.get(i);   
          81.              System.out.println(foo.getName()+"="+foo.getData().toString().trim());   
          82.              List result=foo.elements();       
          83.              if(result!=null||result.size()>0){   
          84.                  this.getXMLValue(result);//遞歸   
          85.              }   
          86.         }          
          87.     }   
          88.        
          89.     /**  
          90.      * 根據節點名獲取值  
          91.      * @param fileName  
          92.      * @param name  
          93.      */  
          94.     public void getElement(String fileName,String name){   
          95.         Document document = this.readXML(fileName);   
          96.         Element root=this.getRootElement(document);   
          97.         // 枚舉名稱為name的節點   
          98.         for ( Iterator i = root.elementIterator(name); i.hasNext();) {   
          99.             Element foo = (Element) i.next();   
          100.             System.out.println(foo.getName()+"="+foo.getData());   
          101.         }   
          102.         // 枚舉所有子節點   
          103. //      for ( Iterator i = root.elementIterator(); i.hasNext(); ) {   
          104. //         Element foo = (Element) i.next();   
          105. //         System.out.println(foo.getName()+"="+foo.getData());   
          106. //      }   
          107.            
          108.     }   
          109.        
          110.     /**  
          111.      * 根據節點名獲取值  
          112.      * @param fileName  
          113.      * @param name  
          114.      */  
          115.     public void getAttribute(Element element,String name){   
          116.         // 枚舉屬性   
          117.         for ( Iterator i = element.attributeIterator(); i.hasNext(); ) {   
          118.            Attribute attribute = (Attribute) i.next();   
          119.            System.out.println(attribute.getName()+"="+attribute.getData());   
          120.         }     
          121.     }   
          122.        
          123.     /**  
          124.      * 得到root節點  
          125.      * @param doc  
          126.      * @return  
          127.      */  
          128.     public Element getRootElement(Document doc){   
          129.            return doc.getRootElement();   
          130.     }   
          131.        
          132.     /**  
          133.      * 讀取xml文件  
          134.      * @param fileName  
          135.      * @return 返回document對象  
          136.      */  
          137.     public Document readXML(String fileName){   
          138.          SAXReader saxReader = new SAXReader();   
          139.          Document document=null;   
          140.           try {   
          141.                document = saxReader.read(new File(fileName));   
          142.           }catch(Exception e){   
          143.               System.out.println("readXML has error:"+e.getMessage());   
          144.               e.printStackTrace();   
          145.           }   
          146.           return document;   
          147.     }   
          148.        
          149.        
          150.        
          151.      /**  
          152.       * 遍歷整個XML文件,獲取所有節點的值與其屬性的值,并放入HashMap中  
          153.       * @param 待遍歷的XML文件  
          154.       */  
          155.      public void iterateWholeXML(String filename){      
          156.           Document document = this.readXML(filename);   
          157.           Element root=this.getRootElement(document);   
          158.           List list=root.elements();   
          159.           this.getXMLValue(list);       
          160.      }   
          161.         
          162.       public static void main(String[] argv){      
          163.           Dom4JPhase dom4j=new Dom4JPhase();      
          164.           dom4j.generateDocument();   
          165.           String fileName="c:/catalog.xml";   
          166.           String elementName="book";   
          167. //        dom4j.generateDocument();   
          168.           long lasting = System.currentTimeMillis();   
          169.           dom4j.iterateWholeXML(fileName);   
          170. //        dom4j.getElement(fileName, elementName);           
          171.           System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + " 毫秒");          
          172.       }     
          173. }  

          rax解析:
          Java代碼 復制代碼
          1. package cn.xml;   
          2.   
          3. /**  
          4.  * yicha   
          5.  * Jul 3, 2008   
          6.  */  
          7.   
          8. import java.net.URL;   
          9. import java.util.Properties;   
          10.   
          11. import org.xml.sax.*;   
          12. import org.xml.sax.helpers.*;   
          13. import javax.xml.parsers.*;   
          14.   
          15.   
          16. /**  
          17.  * SAX 解析  
          18.  * @author yicha  
          19.  *  
          20.  */  
          21. public class SAXReader extends DefaultHandler {   
          22.        
          23.      /*props:用于存放解析器解析出來的的節點和節點對應的屬性,為哈希表  
          24.      * currentName:當前節點的名稱  
          25.      * currentValue:用于存放當前節點所對應的屬性值  
          26.      */  
          27.     private Properties props;   
          28.     private String currentName;   
          29.     private StringBuffer currentValue = new StringBuffer();   
          30.   
          31.       
          32.     public SAXReader() {   
          33.         this.props=new Properties();   
          34.     }   
          35.     
          36.     
          37.     public Properties getPrpos() {   
          38.         return this.props;   
          39.     }   
          40.       
          41.       
          42.     public String getCurrentName(){   
          43.         return currentName;   
          44.     }   
          45.       
          46.       
          47.     /*  
          48.      * 讀取<xxx>中的值xxx并將其付給qname,通知解析器解析當前節點對應的值。同時對currentValue緩沖器清空,用來保存當前qname對應屬性值。  
          49.      * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)  
          50.      */  
          51.    public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{   
          52.         currentValue.delete(0,currentValue.length());   
          53.         this.currentName=qName;   
          54.     }   
          55.       
          56.       
          57.       /*讀取<xxx></xxx>之間的屬性值,并將其首先以字符形式保存至字符數組ch中,并記錄對應長度,以確保以  
          58.        * length為長度的字符為一個整體,然后講字符數組中的內容按照length長度為整體加到currentValue緩沖器中  
          59.        * 每次讀取xml文件后只會在ch中保存當前所解析到的值,currentValue中也只會有當前的節點所對應的唯一值  
          60.      */  
          61.     public void characters(char[] ch,int start,int length)   
          62.     throws SAXException   
          63.     {   
          64.         currentValue.append(ch,start,length);   
          65.     }   
          66.        
          67.     /* 當遇到</xxx>時,將當前的qname,和qname所對應的位于currentValue緩沖器中的值保存到props這個哈希表中去,供外部程序調用  
          68.      * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)  
          69.      */  
          70.     public void endElement(String uri, String localName, String qName)  throws SAXException   {   
          71.         props.put(qName.toLowerCase(), currentValue.toString().trim());   
          72.     }       
          73.        
          74.       
          75.        
          76.     public static void main(String args[]) {   
          77.         long lasting = System.currentTimeMillis();   
          78.         String fileName="c:/catalog.xml";   
          79.         SAXParserFactory sf = SAXParserFactory.newInstance();   
          80.         SAXParser sp;   
          81.         try {   
          82.             sp = sf.newSAXParser();    
          83.             SAXReader reader = new SAXReader();   
          84.             sp.parse(new InputSource(fileName), reader);   
          85.         }    
          86.         catch (Exception e) {   
          87.             e.printStackTrace();   
          88.         }   
          89.         System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");   
          90.     }   
          91.        
          92. }   

          Java代碼 復制代碼
          1. package cn.xml;   
          2.   
          3. import java.net.URL;   
          4. import java.util.Iterator;   
          5. import java.util.Properties;   
          6.   
          7. import javax.xml.parsers.SAXParser;   
          8. import javax.xml.parsers.SAXParserFactory;   
          9.   
          10. /**  
          11.  * yicha   
          12.  * Dec 1, 2008   
          13.  */  
          14.   
          15. public class SaxPhase {   
          16.      private Properties props;      
          17.      public SaxPhase(){   
          18.          props=new Properties();   
          19.      }    
          20.         
          21.      public Properties getProps(){   
          22.             return this.props;   
          23.      }     
          24.     public  void parse(String filename)    throws Exception  {   
          25.             //實例化解析器   
          26.             SAXReader handler = new SAXReader();              
          27.             //實例化用于分析的工廠   
          28.             SAXParserFactory factory = SAXParserFactory.newInstance();            
          29.             //實例化分析類   
          30.             SAXParser parser = factory.newSAXParser();            
          31.             //得到xml文件對應的路徑   
          32.             URL confURL = SAXReader.class.getClassLoader().getResource(filename);   
          33.             try{   
          34.                 parser.parse(confURL.toString(), handler);   
          35.                 props = handler.getPrpos();   
          36.             }finally {            
          37.                  //銷毀已過期對象               
          38.                 factory=null;   
          39.                 parser=null;   
          40.                 handler=null;   
          41.             }   
          42.                
          43.         }          
          44.         /*  
          45.          * 提供給外部程序調用的用于返回程序所對應需要的xml文件屬性的方法  
          46.          */  
          47.      public String getElementValue(String elementName) {   
          48.             //elementValue:對應于elementName的節點的屬性值   
          49.             String elementValue=null;   
          50.             elementValue=props.getProperty(elementName);   
          51.             return elementValue;   
          52.      }   
          53.     /**  
          54.      * @param args  
          55.      */  
          56.     public static void main(String[] args) {   
          57.         SaxPhase sp=new SaxPhase();   
          58.         String filename="testXML.xml";   
          59.         try {   
          60.             sp.parse(filename);   
          61.             Properties props=sp.getProps();   
          62. //          System.out.println(props.size()+"");   
          63.             Iterator it=props.keySet().iterator();   
          64.             while(it.hasNext()){   
          65.                 String key=it.next().toString();   
          66.                 System.out.println(props.get(key)+"");   
          67.             }   
          68. //          System.out.println(sp.getElementValue("driver-class"));   
          69.                
          70.         } catch (Exception e) {        
          71.             e.printStackTrace();   
          72.         }   
          73.   
          74.     }   
          75.   
          76. }  


          轉自:http://canofy.javaeye.com/blog/285107
          posted on 2009-06-22 18:18 胖胖泡泡 閱讀(180) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 开化县| 即墨市| 四平市| 阿图什市| 无极县| 泸西县| 永宁县| 冀州市| 吉林省| 名山县| 荃湾区| 故城县| 美姑县| 宿松县| 司法| 临桂县| 荥阳市| 静宁县| 西乌珠穆沁旗| 昌平区| 万载县| 岐山县| 紫云| 汤原县| 宁远县| 叙永县| 观塘区| 陈巴尔虎旗| 广州市| 昂仁县| 咸阳市| 尖扎县| 延安市| 江北区| 赤壁市| 南城县| 滦平县| 通海县| 宣恩县| 邢台市| 东方市|