jaxp和dom4j的SAX实现方式比较

来源:互联网 发布:7层网络结构 编辑:程序博客网 时间:2024/05/12 21:12
【jaxp的SAX实现方式】

package jaxp;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

importcom.sun.org.apache.xerces.internal.parsers.SAXParser;
public class jaxp
{
 public static void main(String str[])
 {
  SAXXmlReader();
 
 public static void SAXXmlReader()
 {
  String filename="hope.xml";       
    try
    {
     SAXParserFactorysaxfactory=SAXParserFactory.newInstance();
      javax.xml.parsers.SAXParserparser=saxfactory.newSAXParser();
     DefaultHandlerh =newMyHandler();   //事件处理
      parser.parse(filename,h);     
    }
    catch(Exception e)
    {
      System.err.println("Exception:" + e.getMessage());
     
 }
}
class MyHandler extends DefaultHandler//基于事件的。
{
 String s; 
 //目前节点所对应的值
 private String currentValue = null;
 public void startElement(String uri,StringlocalName, String qName, Attributes attr)
 
  if(qName.equalsIgnoreCase("attr"))
    {
        Stringmytitle=attr.getValue("name");
        if(mytitle!=null)
        {
         System.out.println("mytitleis:"+mytitle);         
        }
     
  elseif(qName.equalsIgnoreCase("content"))
  {
    Stringdescription=attr.getValue("description");
    if(description!=null)
    {
       System.out.println("contentdescriptionis:"+description);         
    }
  
 }
 public void endElement(String uri, StringlocalName,String qName)
 {
  System.out.println(""+currentValue);
 }
 public void characters(char[] ch, int start,intlength)
 {
  currentValue = newString(ch,start, length); //得到正在读取的值。
 }
}

【dom4j的SAX实现方法】

public static void ReadXMLBySAX()throwsDocumentException
 {
  List list;
  File f =newFile("hope.xml");
  SAXReader reader =newSAXReader();
  Document doc=reader.read(f);
// read(File file);Reads aDocumentfrom the given File
  // 读取内容
  list=doc.selectNodes("//content");
  Iterator i_content=list.iterator();
  if (i_content.hasNext())
  {
   Elementelement= (Element) i_content.next();
   Stringcontent=element.getText();
   System.out.println("内容是:"+content);
  }
  // 读取标题和时间
  list=doc.selectNodes("//attr/@name");
  if (list != null) {
   Iteratoriter= list.iterator();
   while(iter.hasNext())
   {
    Attributeattribute= (Attribute) iter.next();
    if(attribute.getValue().equals("标题"))
    {
     System.out.println("标题:"+attribute.getParent().getText());
     break;
    }
   }
  }

 }

由此可见,无论是dom4j的哪种方式与jaxp相比,操作都非常简单且直观,特别在选择元素及属性的时候,其优势相对明显。

jaxp是javaapi中自带的一个包,但是dom4j需要我们加入指定的jar文件,其中包括:dom4j-1.6.1.jarh和jaxen-1.1-beta-6.jar两个文件。

原创粉丝点击