<students>
<student fno="01">
<fname>John</fname>
<fsex>男</fsex>
<fage>12</fage>
<address>益阳</address>
</student>
<student fno="02">
<!-- 这里是注释 -->
<fname>Smith</fname>
<fsex>男</fsex>
<fage>23</fage>
<address>益阳</address>
</student>
<student fno="03">
<fname>Anns</fname>
<fsex>女</fsex>
<fage>18</fage>
<address>益阳</address>
</student>
</students>
package com;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
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;
import org.xml.sax.SAXException;
public class DomTest02 {
/**
* 使用递归解析任XML 文档
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*
* */
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(new File("students.xml"));
Element root=doc.getDocumentElement();
parseRoot(root);
}
/**
* 用递归解析任意XmL 文档
*
* @param root 根元素
* */
private static void parseRoot(Element element){
//获得根元素名称
String tagName=element.getNodeName();
//获得根元素的孩子
NodeList children=element.getChildNodes();
System.out.print("<"+tagName);
//获得元素的属性
NamedNodeMap map=element.getAttributes();
//判断是否含有属性
if(null!=map)
{
for(int i=0;i<map.getLength();i++)
{
Attr attr=(Attr)map.item(i);
System.out.print(" "+attr.getName()+"=\""+attr.getValue()+"\"");
}
}
System.out.print(">");
for(int i=0;i<children.getLength();i++)
{
Node node=children.item(i);
short nodetype=node.getNodeType();
//含有子元素
if(nodetype==Node.ELEMENT_NODE)
{
parseRoot((Element)node);
}
//含有文本
else if( nodetype==Node.TEXT_NODE)
{
System.out.print(node.getNodeValue());
}
//含有注释
else if(nodetype==Node.COMMENT_NODE)
{
Comment date=(Comment)node;
System.out.println("<!--"+date.getData()+"-->");
}
}
System.out.print("</"+tagName+">");
}
}