XML--Jaxp-sax解析

sax特色:1:只讀java

               2:僅向前,讀完就刪除內存中的數據ide

               3:佔內存小this

1:讀取全部有用的數據spa

 @Test
 public void test1() throws Exception {
  // 建立解析器
  SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
  // 2:解析xml文件
  sax.parse(new File("./file/users.xml"), new DefaultHandler() {
   private String qName = null;
 
   @Override
   public void startElement(String uri, String localName,String qName, Attributes attr) throws SAXException {
    if (qName.equals("user")) {
     // 獲取id
     String id = attr.getValue("id");
     System.err.println(id);
    } else if (qName.equals("name") || qName.equals("age")) {
     this.qName = qName;
    }
   }
 
   @Override
   // uri命名空間,qName全限定名稱
   public void endElement(String uri, String localName, String qName)
     throws SAXException {
    if (qName.equals("name") || qName.equals("age")) {
     this.qName = null;
    }
   }
 
   @Override
   public void characters(char[] ch, int start, int length)  throws SAXException {
    if (qName != null) {
     String val = new String(ch, start, length);
     System.err.println(val);
    }
   }
  });
 }

2.讀取全部有用的數據封裝到list<bea>code

@Test
 public void query() throws Exception {
  final List<User> 
list = new ArrayList<User>();
  SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
  sax.parse(new File("./file/users.xml"), new DefaultHandler() {
   User u = null;
   private String qName;
 
   @Override
   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (qName.equals("user")) {
     u = new User();
     u.setId(attributes.getValue("id"));
    } else if (qName.equals("name") || qName.equals("age")) {
     this.qName = qName;
    }
   }
 
   @Override
   public void characters(char[] ch, int start, int length) throws SAXException {
    if (qName != null) {
     String val = new String(ch, start, length);
     if (qName.equals("name")) {
      u.setName(val);
     } else {
      u.setAge(Integer.valueOf(val));
     }
    }
   }
 
   @Override
   public void endElement(String uri, String localName, String qName) throws SAXException {
    if (qName.equals("name") || qName.equals("age")) {
     this.qName =null;
    }else if(qName.equals("user")){
     list.add(u);
    }
   }
  });
  System.err.println("封裝的結果是:"+list);
 }
相關文章
相關標籤/搜索