xml解析(dom和sax的区别)

dom(document object model):w3c标准的解析方法,解析时,首先生成dom树。接口由多个厂商实现,比如apache,ibm,sun也有自己的dom解析器。
代码规范:
 DocumentBuilderFactory  dbf = new DocumentBuilderFactory.newInstance();
 DocumentBuilder  db = dbf.newDocumentBuilder();
 Document  doc = db.parse(File f);

dom示意图:

           node
     /|/
 attr character document documenttype element notaion processing
  data            instruction
                 |
                 //
             text comment  documentfragment  entity  entityrefernce
               |
     cdata
    section
sax(simple api for xml):在读入文档是生成相应的事件......

代码:

 
import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserTest {
 public static void main(String[] args) throws Exception{
  SAXParserFactory factory=SAXParserFactory.newInstance();
  SAXParser parser=factory.newSAXParser();
  parser.parse(new File("test01.xml"),new DefaultHandler(){

   public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
    System.out.println(new String(arg0,arg1,arg2));
   }

   public void endElement(String arg0, String arg1, String arg2) throws SAXException {
    System.out.println("</"+arg2+">");
   }

   public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
    System.out.print("<"+arg2);
    for(int i=0;i<arg3.getLength();i++){
     System.out.print(" "+arg3.getQName(i)+"=/""+arg3.getValue(i)+"/"");
    }
    System.out.println(">");
   }
   
  });
 }

}


dom解析可以满足我们的大多数目的,如果你要处理很长的文档,或者只是对部分元素感兴趣,而不关系上下文,建议使用sax。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值