qq_從南_nqCMU0
2019-01-23 13:27
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class bookparse {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("src/lib/book.xml");
NodeList booklist = document.getElementsByTagName("book");
for (int i = 0; i < booklist.getLength(); i++) {
Node node = booklist.item(i);
NamedNodeMap nnms = node.getAttributes();
System.out.println("第" + (i + 1) + "本书:");
for (int j = 0; j < nnms.getLength(); j++) {
NodeList bookchild = node.getChildNodes();
for (int k = 0; k < bookchild.getLength(); k++) {
Node bookvalue = bookchild.item(k);
if (bookvalue.getNodeType() == Node.ELEMENT_NODE) {
System.out.print(bookvalue.getNodeName() + ":");
System.out.println(bookvalue.getTextContent());
}
}
}
System.out.println("");
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
嘿嘿嘿嘿嘿嘿嘿
Java眼中的XML---文件读取
83199 学习 · 431 问题