-------------------------------------------------------xml文件中的内容是-------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="No1">
<name>jacky</name>
<sex>男</sex>
<age>21</age>
<address>成都</address>
</student>
<student id="No2">
<name>mexican</name>
<sex>女</sex>
<age>22</age>
<address>北京</address>
</student>
<student id="No3">
<name>david</name>
<sex>男</sex>
<age>23</age>
<address>上海</address>
</student>
<student id="No4">
<name>android</name>
<sex>男</sex>
<age>24</age>
<address>纽约</address>
</student>
</students>
=======================================================================================================================
package org.demo.dom;
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.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 RecurrenceXMl {
/***
*
* 使用递归方式解析XML
*
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException {
// 构建xml解析工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// 构建具体的xml解析器
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
// 获得当前xml的文档
Document document = documentBuilder.parse("student.xml");
// 获得当前文档的根元素
Element root = document.getDocumentElement();
recurrence(root);
}
// 递归解析xml的方法
private static void recurrence(Element element) {
System.out.print("<" + element.getNodeName());
NodeList childNodes = element.getChildNodes();
// 得到当前节点上的所有属性
NamedNodeMap nodeMap = element.getAttributes();
if (null != nodeMap) {
for (int j = 0; j < nodeMap.getLength(); j++) {
Attr attr = (Attr) nodeMap.item(j);
// 属性的名称
String attrName = attr.getNodeName();
// 属性的值
String attrValue = attr.getNodeValue();
System.out.print(" "+attrName + "=\"" + attrValue+"\"");
}
}
System.out.print(">");
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
// 得到当前节点下的节点
short nodeType = childNode.getNodeType();
// 当前类型是元素类型
if (nodeType == Node.ELEMENT_NODE) {
//继续递归
recurrence((Element) childNode);
}
// 当前元素是文本
else if (nodeType == Node.TEXT_NODE) {
//递归出口
System.out.print(childNode.getNodeValue());
}
}
System.out.println("</" + element.getNodeName() + ">");
}
}