遍历解析xml字符串

package jmst_jy;

import java.io.*;
import java.util.Iterator;

import org.dom4j.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class TestXML {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		stringSS();
	}
	
	public static void stringSS(){
		String strXML = getString();//xml字符串
		Document doc = null;
        try {
        	// 将字符串转为XML
            doc = DocumentHelper.parseText(strXML);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = doc.getRootElement();// 获取根节点
        System.out.println("根节点:" + root.getName()); // 拿到根节点的名称
        JSONArray jsonArray = getElement(root,"");
        System.out.println(jsonArray.toString());
	}
	
	//遍历解析xml
	public static JSONArray getElement(Element root,String qwe){
		qwe +="  ";
		Iterator it = root.elementIterator();
		JSONArray jsonA = new JSONArray();
        while (it.hasNext()) {
            Element element = (Element) it.next();// 一个Item节点
            JSONObject jsonO = new JSONObject();
            jsonO.put("name", element.getName());
            jsonO.put("value", element.getTextTrim());
            System.out.println(qwe+element.getName() + ":" + element.getTextTrim());
            if(element.getName()!=null){
            	JSONArray jsonC = getElement(element,qwe);
            	 jsonO.put("children", jsonC);
            }
            jsonA.add(jsonO);
        }
		return jsonA;
	}
	//读取文件中的文字
	public static String getString(){
		 StringBuffer sb = new StringBuffer();
		try {
		//文件绝对路径
		     File file = new File("C:\\Users\\jmst1701\\Desktop\\xml.txt");
//		    String encoding="GBK";
		     if (file.isFile() && file.exists()) {
		       InputStreamReader isr = new InputStreamReader( new FileInputStream(file) );
		       BufferedReader br = new BufferedReader(isr);
		       String lineTxt = null ;
		      
		       while ((lineTxt = br.readLine()) != null ) {
		        // System.out.println(lineTxt);
		         sb.append(lineTxt);
		       }
		       br.close();
		     } else {
		       System.out.println( "文件不存在!" );
		     }
		   } catch (Exception e) {
		     System.out.println( "文件读取错误!" );
		   }
		return sb.toString();
	}
	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值