您的位置:首页 > 编程语言 > Java开发

用java解析xml

2015-11-17 22:38 429 查看
解析xml.java文件如下:
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class 解析XML {

public static void main(String[] args) {
try {
new 解析XML().jiexi(new File("H:\\employee.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void jiexi(File file) throws FileNotFoundException,IOException{
//将对象读入流中
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
StringBuffer sb = new StringBuffer();
//读取xml数据
while((line = br.readLine())!=null){
sb.append(line+"\n");
}
System.out.println("xml:"+sb.toString());
//开始解析
if(sb.length() > 0) {
//根节点
Element root= null;
try {
root = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))).getDocumentElement();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
//拿出根节点的所有子节点
NodeList nodes = root.getChildNodes();
int count = nodes.getLength();
for (int i = 0; i < count; i++) {
String nodeName = nodes.item(i).getNodeName();
//如果是sex节点
if ("sex".equals(nodeName)) {
System.out.println("sex:"+nodes.item(i).getFirstChild().getNodeValue());
}
//如果是name节点
if ("name".equals(nodeName)) {
//拿出name的子节点
NodeList name_nodes = nodes.item(i).getChildNodes();
int name_count = name_nodes.getLength();
//循环出name节点的每一个子节点
for (int j = 0; j < name_count; j++) {
//如果是name里的last_name
if("last_name".equals(name_nodes.item(j).getNodeName())) {
System.out.println("last_name:"+name_nodes.item(j).getFirstChild().getNodeValue());
}
}
}
}
}
}
}



employee.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<employee>
<name>
<first_name>小林</first_name>
<last_name>陈</last_name>
</name>
<sex>男</sex>
<birthday>1982-1-1</birthday>
<department>行政部</department>
<mobile>13888888888</mobile>
</employee>


执行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml java解析xml