JAVA 文件
Main:
Reader.java
import java.util.List;public class Reader {/*** @author lxh* @param args*/public static void main(String[] args) {try {List<String> list = XmlReader.readXml("dailyreport");System.out.println(list);//输出列表。System.out.println(list.get(2));//输出列表内索引为2的值。} catch (Exception e) {e.printStackTrace();}}}
XmlReader.java
import java.util.*;import java.io.File;import javax.xml.parsers.*;import org.w3c.dom.*;public class XmlReader {public static List<String> readXml(String nodeName) throws Exception {DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document document = db.parse(new File("test.xml"));// 把XML文件解析成DOCUMENT类型Element root = document.getDocumentElement();String NodeName=nodeName; //自选XML中的节点名NodeList list = root.getElementsByTagName(NodeName);// 获得page元素List<String> list2=showElem(list);return list2;}public static List<String> showElem(NodeList nl) {List<String> list = new ArrayList<String>();for (int i = 0; i < nl.getLength(); i++) {Node n = nl.item(i);// 得到父节点// 子节点NodeList childList = n.getChildNodes();for (int x = 0; x < childList.getLength(); x++) {Node childNode = childList.item(x);// 判断取出的值是否属于Element元素,目的是过滤掉if (childNode instanceof Element) {// 得到子节点的名字//String childNodeName = childNode.getNodeName();//System.out.print("节点名:" + childNodeName);// 得到子节点的值String childNodeValue = childNode.getTextContent();list.add(childNodeValue);System.out.println("节点值:" + childNodeValue);}}}return list;}}
test.xml
<?xml version="1.0" encoding="utf-8"?><test><project><code>systemMessage</code><title>标题:系统消息</title><content>概要:您 管理的项目已天未派发新任务</content><sendercode>system</sendercode><sendername>发送者:系统</sendername><receivercode>test</receivercode><receivername>接受者:测试</receivername><state>状态:已读</state><desc>内容:您管理的项目已三天未派发新任务,请注意项目进度</desc><type>类型:systemMessage</type><sendtime>发送时间:2015-8-17</sendtime><tocode>回复</tocode></project><dailyreport><code>systemMessage</code><title>标题:系统消息</title><content>概要:您 已经三天未填写日报务</content><sendercode>system</sendercode><sendername>发送者:系统</sendername><receivercode>test</receivercode><receivername>接受者:测试</receivername><state>状态:已读</state><desc>内容:您 已经三天未填写日报务,请及时填写</desc><type>类型:systemMessage</type><sendtime>发送时间:2015-8-17</sendtime><tocode>回复</tocode></dailyreport></test>
输出结果:
节点值:systemMessage
节点值:标题:系统消息
节点值:概要:您 已经三天未填写日报务
节点值:system
节点值:发送者:系统
节点值:test
节点值:接受者:测试
节点值:状态:已读
节点值:内容:
您 已经三天未填写日报务
节点值:类型:systemMessage
节点值:发送时间:2015-8-17
节点值:回复
[systemMessage, 标题:系统消息, 概要:您 已经三天未填写日报务, system, 发送者:系统, test, 接受者:测试, 状态:已读, 内容:您管理的项目已三天未派发新任务,请注意项目进度, 类型:systemMessage, 发送时间:2015-8-17, 回复]
概要:您 已经三天未填写日报务
