获取node中的值用getTextContent()方法出错,紧急!!!
xml文件内容:
<?xml version="1.0" encoding="GB2312"?>
<employees>
<employee>
<name>丁宏亮</name>
<sex>m</sex>
<age>30</age>
</employee>
<employee>
<name>丁宏亮</name>
<sex>m</sex>
<age>30</age>
</employee>
</employees>
java代码:
import java.io.FileInputStream;
import
java.io.FileNotFoundException;
import java.io.FileOutputStream;
import
java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.Transformer
ConfigurationException;
import
javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import
org.xml.sax.SAXException;
public class DomDemo {
private Document document;
private String fileName;
public void init() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.document = builder.newDocument();
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
}
}
public void parserXml(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //document创建工厂
DocumentBuilder db = dbf.newDocumentBuilder(); //创建document对象
Document document = db.parse(fileName); //将指定路径下的xml解析到document对象中
NodeList employees = document.getChildNodes(); //获取文档的根节点
System.out.println(employees.getLength()+"!!!");
System.out.println(employees.item(0).getNodeName()+"!!!");
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
System.out.println(employeeMeta.getLength());
for (int k = 0; k < employeeMeta.getLength(); k++) {
if(!employeeMeta.item(k).getNodeName().equals("#text")){
System.out.print(employeeMeta.item(k).getNodeName());
System.out.println( employeeMeta.item(k).getTextContent()); //一到此处就报错,我不知道为什么,?
}
}
}
}
System.out.println("解析完毕");
} catch (
FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationExce