java学习

java学习

 

XMLStreamReader光标解析xml文件

public static void test01() {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  InputStream is = null;
  try {
   is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
   XMLStreamReader reader = factory.createXMLStreamReader(is);
   while(reader.hasNext()) {
                        //    System.out.println("------------------------------------------------");
    int type = reader.next();
                                 System.out.println("type---"+type);
    //判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
    if(type==XMLStreamConstants.START_ELEMENT) {//==1,指示事件是一个开始元素
     System.out.println(reader.getName());
                                        String name = reader.getName().toString();
                                        if("book".equals(name)){
                                             System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
                                        }else if("title".equals(name)){
                                             System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
                                        }
                                       
                                        //  System.out.println("==1,指示事件是一个开始元素");
    } else if(type==XMLStreamConstants.CHARACTERS) {//==4指示事件是一些字符
     System.out.println(reader.getText().trim());
                                    // System.out.println("==4指示事件是一些字符");
    } else if(type==XMLStreamConstants.END_ELEMENT) {//==2,指示事件是一个结束元素
     System.out.println("/"+reader.getName());
                                     //  System.out.println("==2,指示事件是一个结束元素");
    }
                                //else if(type==XMLStreamConstants.ATTRIBUTE){
//                                   int count = reader.getAttributeCount();
//                                   System.out.println("count========"+count);
//                                 if(count>0){
//                                     int i=0;
//                                     int[] arr = new int[count];
//                                     while(i<count){
//                                         arr[i]=i;
//                                         i++;
//                                     }
//                                     for(int a : arr){
//                                         System.out.println(reader.getAttributeValue(a));
//                                     }
//                                 }
//                                }
   }
  } catch (XMLStreamException e) {
   e.printStackTrace();
  } finally {
   try {
    if(is!=null) is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

posted on 2013-08-07 13:51 杨军威 阅读(1456) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜