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();
}
}
遍历解析xml字符串
最新推荐文章于 2022-10-21 16:20:55 发布