使用SAXReader读取xml文件

前端之家收集整理的这篇文章主要介绍了使用SAXReader读取xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原XML文件

<?xml version="1.0" encoding="GB2312"?>
<root>
<test>99999</test>
<sys>
<prcscd>5275</prcscd>
<timeout>0</timeout>
</sys>
<comm_req>
<qudaohao>001</qudaohao>
<farendma>9999</farendma>
<jiaoyirq>20151221</jiaoyirq>
<jiaoyijg>018888</jiaoyijg>
<jiaoyigy>0100010</jiaoyigy>
<jiaoyima>5275</jiaoyima>
<waibclma>6600</waibclma>
<test>
<dmkaif>99898989</dmkaif>
<hhh>
<hao>000</hao>
</hhh>
</test>
<waibjymc>c1aaaa</waibjymc>x
<waiblius>QD0011221000000012</waiblius>
<waibriqi>20151221</waibriqi>
<jiaoyilx>1</jiaoyilx>
<ipdizhii>10.91.100.174</ipdizhii>
<zhongdhm>QH-20141117QBBW</zhongdhm>
<zhaiyoms>2</zhaiyoms>
<feiyqrbz>0</feiyqrbz>
<ldbiaozi>0</ldbiaozi>
</comm_req>
<input>
<jiaoyima>C1AAAA</jiaoyima>
<ziduanlb>tranam</ziduanlb>
<ziduanzi>2220.00</ziduanzi>
</input>
</root>

解析的程序

package sunline.subsystem.expr.common.logic;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;


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


public class ReadXmlTest {
public static void main(String[] args) {
File xmlFile = new File("D:/test.xml");//指定路径、
FileInputStream fis = null;
try{
fis = new FileInputStream(xmlFile);
}catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("file not exsit !");
}

SAXReader saxReader = new SAXReader();
saxReader.setEncoding("gbk");
Element rootElement = null;
List<Element> elements = null;
try{
//生成文档实体
Document doc = saxReader.read(fis);
rootElement = doc.getRootElement();
}catch (DocumentException e) {
e.printStackTrace();
}
printValue(rootElement);

}

/*

*使用递归对整个节点进行解析

*/ private static void printValue(Element e){ if (e.elements().size() == 0) {//当节点没有子节点的时候 System.out.println("Name:"+e.getName()+",Value:"+e.getText()); return; } for ( Iterator iterInner = e.elementIterator(); iterInner.hasNext(); ) {//如果该节点存在子节点 Element elementInner = (Element) iterInner.next(); printValue(elementInner); } } }

猜你在找的XML相关文章