FishYu
2015-09-10 18:59
为什么不能用DocumentBuilderFactory对象呢?
他是一个抽象类,你可以看看我写的代码:
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("books.xml");
NodeList nlist = doc.getElementsByTagName("book");
for (int i = 0; i < nlist.getLength(); i++) {
Node book = nlist.item(i);
NamedNodeMap attrs = book.getAttributes();
for (int j = 0; j < attrs.getLength(); j++) {
Node attr = attrs.item(j);
System.out.print("===>> 属性名: " + attr.getNodeName());
System.out.println(", 属性值: " + attr.getNodeValue()+" <<===");
}
NodeList childNodes = book.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node node = childNodes.item(j);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.print("节点名: " + node.getNodeName());
System.out.println(", 节点值: " + node.getTextContent());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Java眼中的XML---文件读取
83199 学习 · 431 问题
相似问题