Dom4j解析XML文档
程序员文章站
2022-04-13 22:08:59
...
进一步学习对于XML文档的操作,用Dom4j进行XML文档的解析,与大家分享代码!
<?xml version="1.0" encoding="GB2312"?> <ZXTRJXLH> <STATUS>Y</STATUS> <NSRSBH>110108722615277</NSRSBH> <NSRINFO> <NSRMC>无</NSRMC> <SWJGDM>无</SWJGDM> </NSRINFO> </ZXTRJXLH>
package dom4j.xml;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jParseXml {
private static String readXml(String url) throws IOException{
//读取xml文件
FileInputStream fis = new FileInputStream(url);
byte[] b = new byte[1024];
int n = 0;
String s = "";
StringBuffer sb = new StringBuffer();
while((n=fis.read(b))!=-1){
s = new String(b,0,n);//把字节数组中所读取到的字节构建String,
//防止最后一次的多读
sb.append(s);
}
return sb.toString();
}
private static String[] parseXml(String xml) {
String flag[] = { "", "", "", "", "" };
try {
SAXReader reader = new SAXReader();
reader.setEncoding("GBK");
Document doc = reader.read(new StringReader(xml));
Element root = doc.getRootElement();
List rootList = root.elements();
if (rootList.size() > 0) {
Element element = (Element) root.element("STATUS");
flag[0] = element.getText();
element = (Element) root.element("NSRSBH");
flag[1] = element.getText();
List list = root.elements("NSRINFO");
if (list.size() > 0) {
for (int k = 0; k < list.size(); k++) {
Element ele = (Element) list.get(k);
// 纳税人名称
element = (Element) ele.element("NSRMC");
flag[2] = element.getText();
// 税务机关代码
element = (Element) ele.element("SWJGDM");
flag[3] = element.getText();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) throws IOException {
String url = "D:\\myxml.xml";
String s = Dom4jParseXml.readXml(url);
String[] ret = Dom4jParseXml.parseXml(s);
System.out.println(ret[1]);
}
}