代码
List<book> list = new ArrayList<book>();
Document doc = new DOCUntil().getDocument("src/ww/t/qp/books.xml");
Element root = doc.getDocumentElement();
NodeList books = root.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element n1 = (Element) books.item(i);
NodeList nodeList = n1.getChildNodes();
String a1 = null;
String a2 = null;
String a3 = null;
for (int j = 0; j < nodeList.getLength(); j++) {
Element e2 = (Element) nodeList.item(j);
if (e2.getNodeName().equals("author")) {
a1 = e2.getTextContent();
}
if (e2.getNodeName().equals("title")) {
a2 = e2.getTextContent();
}
if (e2.getNodeName().equals("description")) {
a3 = e2.getTextContent();
}
}
list.add(new book(new Integer(n1.getAttribute("id")), a1, a2, a3));
}
System.out.println(list.toString());
报错
报错代码
Element e2 = (Element) nodeList.item(j);
分析
getChildNodes获取的是全部子节点,在 xml 文档节点前存在 回车,制表符等 都会占用一个节点Node( 如#text ),这一类Node是无法转为Element,会抛com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element。
解决方案
1.直接使用Node对象进行操作
2.在强转前进行 if 判断标签