您的位置:首页 > 其它

XML小练习:利用DOM解析XML(利用递归,实用性强)

2015-05-26 12:30 375 查看
XML文件(student.xml):


<?xml version="1.0" encoding="utf-8"?>
<学生名册 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="student.xsd" >
<!-- 这不是演习,这不是演习 -->
<学生 学号="1">
<姓名>张三</姓名>
<性别>男</性别>
<年龄>20</年龄>
</学生>
<学生 学号="2">
<姓名>李四</姓名>
<性别>女</性别>
<年龄>19</年龄>
</学生>
<学生 学号="3">
<姓名>王五</姓名>
<性别>男</性别>
<年龄>21</年龄>
</学生>
</学生名册>


JAVA实现:
package com.xml.dom;

import java.io.File;

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

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Domtest2 {
public static void main(String[] args) throws Exception {

// 获取DOM解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 获得具体的DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
// 解析XML文档,获得Document对象(根结点)
Document document = db.parse(new File("student.xml"));

//获取根元素
Element root = document.getDocumentElement();

parseElement(root);// 开始解析

System.out.println("\n\nxml文件解析完成");
}

private static void parseElement(Element element) {
String tagName = element.getNodeName();

System.out.print("<" + tagName);

parseAttr(element);

NodeList children = element.getChildNodes();

for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);

short nodeType = node.getNodeType();

if (nodeType == Node.ELEMENT_NODE)// 如果是元素格式
{
parseElement((Element) node);// 递归
} else if (nodeType == Node.TEXT_NODE)// 如果是文本格式,直接输出
{
System.out.print(node.getNodeValue());
} else if (nodeType == Node.COMMENT_NODE)// 如果是注释格式,获取注释内容后输出
{
System.out.print("<!--");
Comment comment = (Comment) node;
String data = comment.getData();
System.out.print(data + "-->");
}
}
System.out.print("</" + tagName + ">");
}

// 解析该元素是否有属性
private static void parseAttr(Element element) {
NamedNodeMap map = element.getAttributes();

if (map != null) {
for (int i = 0; i < map.getLength(); i++) {
System.out.print(" | " + map.item(i).getNodeName() + "="
+ map.item(0).getNodeValue());
}
System.out.print(">");
} else {
System.out.print(">");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  XML DOM 递归