日期:2014-05-20  浏览次数:20761 次

dom解析xml文件可以找得到,解析不出结果,具体见正文
读取程序---------------------------------------------------------------
package com.yuyi.xml;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.w3c.dom.*;

import javax.xml.parsers.*;

public class XmlUtil {

public Document getDocument(String path){
try{
File file = new File(path);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
System.out.println("factory: "+factory);
DocumentBuilder builder = factory.newDocumentBuilder(); 
System.out.println("builder: "+builder);
Document doc = builder.parse(file);
System.out.println("doc:"+ doc);
BufferedReader br = new BufferedReader(new FileReader(file));
String context;
while((context = br.readLine())!=null){
System.out.println(context);
}
System.out.println("doc: "+doc);
return doc;
}catch(Exception e){
e.printStackTrace();
return null;
}
}

public static void main(String[] args) {

XmlUtil xmlUtil = new XmlUtil();
String path = "./src/bean.xml";
Document doc = xmlUtil.getDocument(path);
System.out.println("doc: "+doc);
}
}

XML文件---------------------------------------------------------------
<?xml version="1.0" encoding="gbk"?><users><user id="0"><name>zhangsan</name><password>lisi</password></user></users>

运行结果---------------------------------------------------------------
factory: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl@1172e08
builder: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl@186db54
doc:[#document: null]
<?xml version="1.0" encoding="gbk"?><users><user id="0"><name>zhangsan</name><password>lisi</password></user></users>

doc: [#document: null]




------解决方案--------------------
package dom;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

/**
 * DOM解析XML文档示例
 */
public class DOMParser {
public DOMParser() {
}
public static void main(String[] args) throws Exception{
DOMParser domparser = new DOMParser();
domparser.parseXMLFile("src/file/student.xml");
}
/**
* 解析文档
* @param fileName
*/
public void parseXMLFile(String fileName) throws Exception{
File file = new File(fileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
doc.normalize();

//获得根元素StudentInfo
Element elmtInfo = doc.getDocumentElement();

//得到所有student元素
NodeList nlStudent = elmtInfo.getElementsByTagName("student");

System.out.println("XML文件开始解析--By DOM");
System.out.println();

//循环输出每一个学生成绩
for (int i = 0; i < nlStudent.getLength(); i++) {

//当前student元素
Element elmtStudent = (Element) nlStudent.item(i);

NodeList nlCurrent = elmtStudent.getElementsByTagName("name");