java读取XMl数据

JAVA程序如下:
package com.liufei.XML;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
* 在java中解析XML文件
* @author 刘飞
*/
public class XMLParse {

/**
*
* @param args
*/
public static void main(String[] args) {
File file = new File("E://workspace/XML/src/com/liufei/XML/Users.xml");

Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(file);
} catch (IOException ioe) {
System.out.println("不能找到此XML文件!");
} catch (Exception e) {
System.out.println(e.getMessage());
}

NodeList users = doc.getElementsByTagName("user");
Element userElement;
for (int i = 0; i < users.getLength(); i++) {
userElement = (Element) users.item(i);
String id = userElement.getAttribute("id");
System.out.println("用户编号:" + id);
String name = doc.getElementsByTagName("name").item(i)
.getFirstChild().getNodeValue();
System.out.println("用户姓名:" + name);
String age = doc.getElementsByTagName("age").item(i)
.getFirstChild().getNodeValue();
System.out.println("用户年龄:" + age);
String sex = doc.getElementsByTagName("sex").item(i)
.getFirstChild().getNodeValue();
System.out.println("用户性别:" + sex);
System.out.println("*****************");
}
}

}


XML程序如下:

<?xml version="1.0" encoding="gb2312"?>
<users>
<user id="1">

<name>刘培</name>
<age>21</age>
<sex>男</sex>
</user>
<user id="2">

<name>李然</name>
<age>22</age>
<sex>女</sex>
</user>
<user id="3">

<name>明刚</name>
<age>19</age>
<sex>男</sex>
</user>
<user id="4">

<name>刘飞</name>
<age>22</age>
<sex>男</sex>
</user>
</users>

你可能感兴趣的:(java,xml)