1 XmlJavaImpl.java
package cuigh.xml.java;
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.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* 功能:演示JAVA自带DOM解析XML功能
* 日期:20151218
* 说明:JDK1.6
* */
public class XmlJavaImpl {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("bin\\test.xml");
Document doc = (Document) builder.parse(file);
Element root = doc.getDocumentElement();
System.out.println("根元素:"+root.getNodeName());
//获得root元素的子元素
NodeList children = (NodeList) root.getChildNodes();
for(int i=0;i
{
Node item = children.item(i);
System.out.println("--root的子元素:"+item.getNodeName());
//只读取子元素
if(item instanceof Element){
System.out.println();
//读取叶子结点内容
Text textNode = (Text) item.getFirstChild();
String text = textNode.getData().trim();
System.out.println("----root 的子元素为:"+item.getNodeName()+"--叶子结点内容:"+text);
}
}
}
}
2 test.xml
宋体
36