<学生名册>
<学生 学号="1">
<姓名>张三</姓名>
<性别>男</性别>
<年龄>20</年龄>
</学生>
<学生 学号="2">
<姓名>李四</姓名>
<性别>女</性别>
<年龄>19</年龄>
</学生>
<学生 学号="3">
<姓名>王五</姓名>
<性别>男</性别>
<年龄>21</年龄>
</学生>
</学生名册>
上面是XML
import java.io.File;
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;
public class DOM_XML_1 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//获得解析工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//获得解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//获得根元素节点
Document doc = db.parse(new File("student.xml"));
//得到根元素
Element root = doc.getDocumentElement();
parseElement(root);
}
//用递归实现解析,并给与输出
private static void parseElement(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);
String attrName = attr.getName();
String attrValue = attr.getValue();
System.out.print(" " + attrName + "=\"" + attrValue +"\"");
}
}
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){
//实现递归
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("-->");
}
}
System.out.print("</" +tagName +">");
}
}