dom解析xml文件

package com.zm.dom;

import java.io.File;

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

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 Dom1 {

/**
* beckham
* Aug 11, 2009 9:32:46 AM
* dom操作
*/
public static void main(String[] args) {
try {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder() ;
Document doc = db.parse(new File("students.xml")) ;

//获取student元素
NodeList nl = doc.getElementsByTagName("student") ;
//student元素的个数
int len = nl.getLength() ;
//循环student
for(int i=0;i<len;i++){
Element elname = (Element)nl.item(i) ;
//获取属性节点
System.out.println(elname.getAttribute("sn"));
NamedNodeMap map = elname.getAttributes() ;
//获取每个student元素下面的节点
Node ndname = elname.getElementsByTagName("name").item(0) ;
Node agenode = elname.getElementsByTagName("age").item(0) ;
//获取文本节点的值,获取该节点的子节点

int ll = map.getLength() ;
for(int j=0;j<ll;j++){
System.out.println(map.item(j).getNodeName()+"+++++++++++++++"+map.item(j).getNodeValue());
}
//文本节点的值是第一个子节点的值
String name = ndname.getFirstChild().getNodeValue() ;
String age = agenode.getFirstChild().getNodeValue() ;
System.out.println(name);
System.out.println(age);
}
} catch (Exception e) {
e.printStackTrace() ;
}
}

}

你可能感兴趣的:(xml,J#)