解析XML文件(字符串)的两种方法-----SAXReader 与 DocumentHelper

一、用SAXReader 方式解析:实例测试类TestXML

 

  package *

 

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

 

public class TestXml {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   // TODO Auto-generated method stub
   //定义要解析的XML字符串
   String transMessage = ""
     + ""
     + ""
     + ""
     + ""
     + "
" + "
";
   // 创建xml解析对象
   SAXReader reader = new SAXReader();
   // 定义一个文档
   Document document = null;
   //将字符串转换为
   document = reader.read(new ByteArrayInputStream(transMessage
     .getBytes("GBK")));
   // 得到xml的根节点(message)
   Element root = document.getRootElement();
   //定义子循环体的变量
   Element ticket=null;
   
   Iterator tickets = null;
   for (tickets = root.element("body").element("ticketNotify").elementIterator(); tickets.hasNext();) {
    ticket = (Element) tickets.next();
    System.out.print(ticket.attributeValue("id")+"  ");
    System.out.print(ticket.attributeValue("dealTime")+"  ");
    System.out.println(ticket.attributeValue("status"));
    
    
    
   }
   //Element.asXML方法,获得包括该标签的所有XML数据
   System.out.println(root.element("body").asXML());
   
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

 

二、DocumentHelper 方式解析:实例测试类TestXML

 

package *;

 

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

 

public class TestXml {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   // TODO Auto-generated method stub
   //定义要解析的XML字符串
   String transMessage = ""
     + ""
     + ""
     + ""
     + ""
     + "
" + "
";
   // 创建xml解析对象
//   SAXReader reader = new SAXReader();
   // 定义一个文档
   Document document = null;
   //将字符串转换为
//   document = reader.read(new ByteArrayInputStream(transMessage
//     .getBytes("GBK")));
   
   document = DocumentHelper.parseText(transMessage);
   // 得到xml的根节点(message)
   Element root = document.getRootElement();
   //定义子循环体的变量
   Element ticket=null;
   
   Iterator tickets = null;
   for (tickets = root.element("body").element("ticketNotify").elementIterator(); tickets.hasNext();) {
    ticket = (Element) tickets.next();
    System.out.print(ticket.attributeValue("id")+"  ");
    System.out.print(ticket.attributeValue("dealTime")+"  ");
    System.out.println(ticket.attributeValue("status"));
    
    
    
   }
   //Element.asXML方法,获得包括该标签的所有XML数据
   System.out.println(root.element("body").asXML());
   
   
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

你可能感兴趣的:(java帮助类)