62,625
社区成员
发帖
与我相关
我的任务
分享
package cn.jbit.exercise14_4;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlDom {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("D:\\student.xml");
NodeList nl = doc.getElementsByTagName("student");
String id = null;
//String nodeName = null;
String nodeValue = null;
System.out.println("XML文档中共有"+nl.getLength()+"个学生:");
System.out.println("ID\t\tName\t\tAge\t\tSchool");
for(int i = 0; i < nl.getLength(); i++){
StringBuffer sb = new StringBuffer();
Node stu = nl.item(i);
Element elmt = (Element) stu;
id = elmt.getAttribute("id");
sb = sb.append(id+"\t\t");
for(Node node = stu.getFirstChild(); node !=null; node = node.getNextSibling()){
if(node.getNodeType() == Node.ELEMENT_NODE){
//nodeName = node.getNodeName();
nodeValue = node.getFirstChild().getNodeValue();
sb.append(nodeValue+"\t\t");
}
}
System.out.println(sb.toString());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
