春天的光輝

          把春天的氣息和光芒灑滿大地,沐浴著身邊的每一個人... ...

           

          2007年1月17日

          2007年流行的10句話!


          2007年流行的10句話:至理名言呀,不看絕對后

          悔,嗯,不相信,不要看了


          1,騎白馬的不一定是王子,他可能是唐僧;

          2,帶翅膀的也不一定是天使,媽媽說,那是鳥人。

          3,水至清則無魚,人至賤則無敵!

          4,走自己的路,讓別人打車去吧。

          5,穿別人的鞋,走自己的路,讓他們找去吧。

          6,我不是隨便的人,我隨便起來不是人。

          7,女人無所謂正派,正派是因為受到的引誘不夠;男人無所謂忠誠,忠誠是因為背叛的籌碼太低。

          8,聰明的女人對付男人,而笨女人對付女人;

          9,站的更高,尿的更遠。

          10,一個大學生的最低奮斗目標:農婦,山泉,有點田

          呵呵,寫的有點意思。

          posted @ 2007-01-17 17:18 春輝 閱讀(216) | 評論 (0)編輯 收藏

          2006年10月13日

          Java中四種XML解析技術之不完全測試 【轉】

          在平時工作中,難免會遇到把XML作為數據存儲格式。面對目前種類繁多的解決方案,哪個最適合我們呢?在這篇文章中,我對這四種主流方案做一個不完全評測,僅僅針對遍歷XML這塊來測試,因為遍歷XML是工作中使用最多的(至少我認為)。

            預備

            測試環境:

            AMD毒龍1.4G OC 1.5G、256M DDR333、Windows2000 Server SP4、Sun JDK 1.4.1+Eclipse 2.1+Resin 2.1.8,在Debug模式下測試。

            XML文件格式如下:

            <?xml version="1.0" encoding="GB2312"?><RESULT><VALUE>

            <NO>A1234</NO>

           ?。糀DDR>四川省XX縣XX鎮XX路X段XX號</ADDR></VALUE><VALUE>

           ?。糔O>B1234</NO>

            <ADDR>四川省XX市XX鄉XX村XX組</ADDR></VALUE></RESULT>

            測試方法:

            采用JSP端調用Bean(至于為什么采用JSP來調用,請參考:http://blog.csdn.net/rosen/archive/2004/10/15/138324.aspx),讓每一種方案分別解析10K、100K、1000K、10000K的XML文件,計算其消耗時間(單位:毫秒)。

            JSP文件:

            <%@ page contentType="text/html; charset=gb2312" %><%@ page import="com.test.*"%>

            <html><body><%String args[]={""};MyXMLReader.main(args);%></body></html>

            測試

            首先出場的是DOM(JAXP Crimson解析器)

            DOM是用與平臺和語言無關的方式表示XML文檔的官方W3C標準。DOM是以層次結構組織的節點或信息片斷的集合。這個層次結構允許開發人員在樹中尋找特定信息。分析該結構通常需要加載整個文檔和構造層次結構,然后才能做任何工作。由于它是基于信息層次的,因而DOM被認為是基于樹或基于對象的。DOM以及廣義的基于樹的處理具有幾個優點。首先,由于樹在內存中是持久的,因此可以修改它以便應用程序能對數據和結構作出更改。它還可以在任何時候在樹中上下導航,而不是像SAX那樣是一次性的處理。DOM使用起來也要簡單得多。

            另一方面,對于特別大的文檔,解析和加載整個文檔可能很慢且很耗資源,因此使用其他手段來處理這樣的數據會更好。這些基于事件的模型,比如SAX。

            Bean文件:

            package com.test;

            import java.io.*;import java.util.*;import org.w3c.dom.*;import javax.xml.parsers.*;

            public class MyXMLReader{

            public static void main(String arge[]){

            long lasting =System.currentTimeMillis();

            try{

             File f=new File("data_10k.xml");

             DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

             DocumentBuilder builder=factory.newDocumentBuilder();

             Document doc = builder.parse(f);

             NodeList nl = doc.getElementsByTagName("VALUE");

             for (int i=0;i<nl.getLength();i++){

              System.out.print("車牌號碼:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());

              System.out.println("車主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());

            }

            }catch(Exception e){

             e.printStackTrace();

            }

            System.out.println("運行時間:"+(System.currentTimeMillis() - lasting)+"毫秒");}}

            10k消耗時間:265 203 219 172

            100k消耗時間:9172 9016 8891 9000

            1000k消耗時間:691719 675407 708375 739656

            10000k消耗時間:OutOfMemoryError

            接著是SAX

            這種處理的優點非常類似于流媒體的優點。分析能夠立即開始,而不是等待所有的數據被處理。而且,由于應用程序只是在讀取數據時檢查數據,因此不需要將數據存儲在內存中。這對于大型文檔來說是個巨大的優點。事實上,應用程序甚至不必解析整個文檔;它可以在某個條件得到滿足時停止解析。一般來說,SAX還比它的替代者DOM快許多。
            選擇DOM還是選擇SAX?

            對于需要自己編寫代碼來處理XML文檔的開發人員來說,

            選擇DOM還是SAX解析模型是一個非常重要的設計決策。

            DOM采用建立樹形結構的方式訪問XML文檔,而SAX采用的事件模型。

            DOM解析器把XML文檔轉化為一個包含其內容的樹,并可以對樹進行遍歷。用DOM解析模型的優點是編程容易,開發人員只需要調用建樹的指令,然后利用navigation APIs訪問所需的樹節點來完成任務??梢院苋菀椎奶砑雍托薷臉渲械脑?。然而由于使用DOM解析器的時候需要處理整個XML文檔,所以對性能和內存的要求比較高,尤其是遇到很大的XML文件的時候。由于它的遍歷能力,DOM解析器常用于XML文檔需要頻繁的改變的服務中。

            SAX解析器采用了基于事件的模型,它在解析XML文檔的時候可以觸發一系列的事件,當發現給定的tag的時候,它可以激活一個回調方法,告訴該方法制定的標簽已經找到。SAX對內存的要求通常會比較低,因為它讓開發人員自己來決定所要處理的tag。特別是當開發人員只需要處理文檔中所包含的部分數據時,SAX這種擴展能力得到了更好的體現。但用SAX解析器的時候編碼工作會比較困難,而且很難同時訪問同一個文檔中的多處不同數據。

            Bean文件:

            package com.test;import org.xml.sax.*;import org.xml.sax.helpers.*;import javax.xml.parsers.*;

            public class MyXMLReader extends DefaultHandler {

            java.util.Stack tags = new java.util.Stack();

            public MyXMLReader() {

            super();}

            public static void main(String args[]) {

            long lasting = System.currentTimeMillis();

            try {

             SAXParserFactory sf = SAXParserFactory.newInstance();

             SAXParser sp = sf.newSAXParser();

             MyXMLReader reader = new MyXMLReader();

             sp.parse(new InputSource("data_10k.xml"), reader);

            } catch (Exception e) {

             e.printStackTrace();

            }

            System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");}

            public void characters(char ch[], int start, int length) throws SAXException {

            String tag = (String) tags.peek();

            if (tag.equals("NO")) {

             System.out.print("車牌號碼:" + new String(ch, start, length));}if (tag.equals("ADDR")) {

            System.out.println("地址:" + new String(ch, start, length));}}

            public void startElement(String uri,String localName,String qName,Attributes attrs) {

            tags.push(qName);}}

            10k消耗時間:110 47 109 78

            100k消耗時間:344 406 375 422

            1000k消耗時間:3234 3281 3688 3312

            10000k消耗時間:32578 34313 31797 31890 30328

            然后是JDOM http://www.jdom.org/

            JDOM的目的是成為Java特定文檔模型,它簡化與XML的交互并且比使用DOM實現更快。由于是第一個Java特定模型,JDOM一直得到大力推廣和促進。正在考慮通過“Java規范請求JSR-102”將它最終用作“Java標準擴展”。從2000年初就已經開始了JDOM開發。

            JDOM與DOM主要有兩方面不同。首先,JDOM僅使用具體類而不使用接口。這在某些方面簡化了API,但是也限制了靈活性。第二,API大量使用了Collections類,簡化了那些已經熟悉這些類的Java開發者的使用。

            JDOM文檔聲明其目的是“使用20%(或更少)的精力解決80%(或更多)Java/XML問題”(根據學習曲線假定為20%)。JDOM對于大多數Java/XML應用程序來說當然是有用的,并且大多數開發者發現API比DOM容易理解得多。JDOM還包括對程序行為的相當廣泛檢查以防止用戶做任何在XML中無意義的事。然而,它仍需要您充分理解XML以便做一些超出基本的工作(或者甚至理解某些情況下的錯誤)。這也許是比學習DOM或JDOM接口都更有意義的工作。

            JDOM自身不包含解析器。它通常使用SAX2解析器來解析和驗證輸入XML文檔(盡管它還可以將以前構造的DOM表示作為輸入)。它包含一些轉換器以將JDOM表示輸出成SAX2事件流、DOM模型或XML文本文檔。JDOM是在Apache許可證變體下發布的開放源碼。

            Bean文件:

            package com.test;

            import java.io.*;import java.util.*;import org.jdom.*;import org.jdom.input.*;

            public class MyXMLReader {

            public static void main(String arge[]) {

            long lasting = System.currentTimeMillis();

            try {

             SAXBuilder builder = new SAXBuilder();

             Document doc = builder.build(new File("data_10k.xml"));

             Element foo = doc.getRootElement();

             List allChildren = foo.getChildren();

             for(int i=0;i<allChildren.size();i++) {

              System.out.print("車牌號碼:" + ((Element)allChildren.get(i)).getChild("NO").getText());

              System.out.println("車主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());

             }

            } catch (Exception e) {

             e.printStackTrace();

            }

            System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");}}

            10k消耗時間:125 62 187 94

            100k消耗時間:704 625 640 766

            1000k消耗時間:27984 30750 27859 30656

            10000k消耗時間:OutOfMemoryError

            最后是DOM4J http://dom4j.sourceforge.net/

            雖然DOM4J代表了完全獨立的開發結果,但最初,它是JDOM的一種智能分支。它合并了許多超出基本XML文檔表示的功能,包括集成的XPath支持、XML Schema支持以及用于大文檔或流化文檔的基于事件的處理。它還提供了構建文檔表示的選項,它通過DOM4J API和標準DOM接口具有并行訪問功能。從2000下半年開始,它就一直處于開發之中。

            為支持所有這些功能,DOM4J使用接口和抽象基本類方法。DOM4J大量使用了API中的Collections類,但是在許多情況下,它還提供一些替代方法以允許更好的性能或更直接的編碼方法。直接好處是,雖然DOM4J付出了更復雜的API的代價,但是它提供了比JDOM大得多的靈活性。

            在添加靈活性、XPath集成和對大文檔處理的目標時,DOM4J的目標與JDOM是一樣的:針對Java開發者的易用性和直觀操作。它還致力于成為比JDOM更完整的解決方案,實現在本質上處理所有Java/XML問題的目標。在完成該目標時,它比JDOM更少強調防止不正確的應用程序行為。

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

            Bean文件:

            package com.test;

            import java.io.*;import java.util.*;import org.dom4j.*;import org.dom4j.io.*;

            public class MyXMLReader {

            public static void main(String arge[]) {

            long lasting = System.currentTimeMillis();

            try {

             File f = new File("data_10k.xml");

             SAXReader reader = new SAXReader();

             Document doc = reader.read(f);

             Element root = doc.getRootElement();

             Element foo;

             for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {

              foo = (Element) i.next();

              System.out.print("車牌號碼:" + foo.elementText("NO"));

              System.out.println("車主地址:" + foo.elementText("ADDR"));

             }

            } catch (Exception e) {

             e.printStackTrace();

            }

            System.out.println("運行時間:" + (System.currentTimeMillis() - lasting) + "毫秒");}}

            10k消耗時間:109 78 109 31

            100k消耗時間:297 359 172 312

            1000k消耗時間:2281 2359 2344 2469

            10000k消耗時間:20938 19922 20031 21078

            JDOM和DOM在性能測試時表現不佳,在測試10M文檔時內存溢出。在小文檔情況下還值得考慮使用DOM和JDOM。雖然JDOM的開發者已經說明他們期望在正式發行版前專注性能問題,但是從性能觀點來看,它確實沒有值得推薦之處。另外,DOM仍是一個非常好的選擇。DOM實現廣泛應用于多種編程語言。它還是許多其它與XML相關的標準的基礎,因為它正式獲得W3C推薦(與基于非標準的Java模型相對),所以在某些類型的項目中可能也需要它(如在JavaScript中使用DOM)。

            SAX表現較好,這要依賴于它特定的解析方式。一個SAX檢測即將到來的XML流,但并沒有載入到內存(當然當XML流被讀入時,會有部分文檔暫時隱藏在內存中)。

            無疑,DOM4J是這場測試的獲勝者,目前許多開源項目中大量采用DOM4J,例如大名鼎鼎的Hibernate也用DOM4J來讀取XML配置文件。如果不考慮可移植性,那就采用DOM4J吧!(文/rosen)(轉載文章請保留出處:Java家(www.javajia.com))

          更多精彩文章:主題文章: Java中四種XML解析技術之不完全測試

          posted @ 2006-10-13 14:40 春輝 閱讀(206) | 評論 (0)編輯 收藏

          dom4j xml解析

          Parsing XML

          One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

          import java.net.URL;
          
          import org.dom4j.Document;
          import org.dom4j.DocumentException;
          import org.dom4j.io.SAXReader;
          
          public class Foo {
          
              public Document parse(URL url) throws DocumentException {
                  SAXReader reader = new SAXReader();
                  Document document = reader.read(url);
                  return document;
              }
          }
          

          Using Iterators

          A document can be navigated using a variety of methods that return standard Java Iterators. For example

              public void bar(Document document) throws DocumentException {
          
                  Element root = document.getRootElement();
          
                  // iterate through child elements of root
                  for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
                      Element element = (Element) i.next();
                      // do something
                  }
          
                  // iterate through child elements of root with element name "foo"
                  for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
                      Element foo = (Element) i.next();
                      // do something
                  }
          
                  // iterate through attributes of root 
                  for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
                      Attribute attribute = (Attribute) i.next();
                      // do something
                  }
               }
          

          Powerful Navigation with XPath

          In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

              public void bar(Document document) {
                  List list = document.selectNodes( "http://foo/bar" );
          
                  Node node = document.selectSingleNode( "http://foo/bar/author" );
          
                  String name = node.valueOf( "@name" );
              }
          

          For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

              public void findLinks(Document document) throws DocumentException {
          
                  List list = document.selectNodes( "http://a/@href" );
          
                  for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                      Attribute attribute = (Attribute) iter.next();
                      String url = attribute.getValue();
                  }
              }
          

          If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

          Fast Looping

          If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

              public void treeWalk(Document document) {
                  treeWalk( document.getRootElement() );
              }
          
              public void treeWalk(Element element) {
                  for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
                      Node node = element.node(i);
                      if ( node instanceof Element ) {
                          treeWalk( (Element) node );
                      }
                      else {
                          // do something....
                      }
                  }
              }
          

          Creating a new XML document

          Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.

          import org.dom4j.Document;
          import org.dom4j.DocumentHelper;
          import org.dom4j.Element;
          
          public class Foo {
          
              public Document createDocument() {
                  Document document = DocumentHelper.createDocument();
                  Element root = document.addElement( "root" );
          
                  Element author1 = root.addElement( "author" )
                      .addAttribute( "name", "James" )
                      .addAttribute( "location", "UK" )
                      .addText( "James Strachan" );
                  
                  Element author2 = root.addElement( "author" )
                      .addAttribute( "name", "Bob" )
                      .addAttribute( "location", "US" )
                      .addText( "Bob McWhirter" );
          
                  return document;
              }
          }
          

          Writing a document to a file

          A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

            FileWriter out = new FileWriter( "foo.xml" );
            document.write( out );
          

          If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

          import org.dom4j.Document;
          import org.dom4j.io.OutputFormat;
          import org.dom4j.io.XMLWriter;
          
          public class Foo {
          
              public void write(Document document) throws IOException {
          
                  // lets write to a file
                  XMLWriter writer = new XMLWriter(
                      new FileWriter( "output.xml" )
                  );
                  writer.write( document );
                  writer.close();
          
          
                  // Pretty print the document to System.out
                  OutputFormat format = OutputFormat.createPrettyPrint();
                  writer = new XMLWriter( System.out, format );
                  writer.write( document );
          
                  // Compact format to System.out
                  format = OutputFormat.createCompactFormat();
                  writer = new XMLWriter( System.out, format );
                  writer.write( document );
              }
          }
          

          Converting to and from Strings

          If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

                  Document document = ...;
                  String text = document.asXML();
          

          If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

                  String text = "<person> <name>James</name> </person>";
                  Document document = DocumentHelper.parseText(text);
          

          Styling a Document with XSLT

          Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.

          import javax.xml.transform.Transformer;
          import javax.xml.transform.TransformerFactory;
          
          import org.dom4j.Document;
          import org.dom4j.io.DocumentResult;
          import org.dom4j.io.DocumentSource;
          
          public class Foo {
          
              public Document styleDocument(
                  Document document, 
                  String stylesheet
              ) throws Exception {
          
                  // load the transformer using JAXP
                  TransformerFactory factory = TransformerFactory.newInstance();
                  Transformer transformer = factory.newTransformer( 
                      new StreamSource( stylesheet ) 
                  );
          
                  // now lets style the given document
                  DocumentSource source = new DocumentSource( document );
                  DocumentResult result = new DocumentResult();
                  transformer.transform( source, result );
          
                  // return the transformed document
                  Document transformedDoc = result.getDocument();
                  return transformedDoc;
              }
          }
          

          posted @ 2006-10-13 11:15 春輝 閱讀(1368) | 評論 (1)編輯 收藏

          僅列出標題  

          導航

          統計

          常用鏈接

          留言簿(1)

          隨筆檔案

          文章分類

          文章檔案

          我的鏈接

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 万全县| 大悟县| 兴文县| 修水县| 通河县| 湄潭县| 收藏| 湛江市| 浦江县| 长汀县| 许昌县| 富顺县| 清新县| 社会| 万荣县| 辰溪县| 开封县| 余江县| 宁安市| 友谊县| 新和县| 内江市| 祁门县| 丰台区| 修文县| 县级市| 宁远县| 常熟市| 都江堰市| 峡江县| 澄城县| 岳西县| 连州市| 灵丘县| 阳东县| 清涧县| 卢龙县| 斗六市| 无棣县| 宝丰县| 武义县|