java中的xml
为什么不能用DocumentBuilderFactory对象呢?
为什么不能用DocumentBuilderFactory对象呢?
2015-09-10
他是一个抽象类,你可以看看我写的代码:
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();
}
}
举报