package dao;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
//需要dom 解析器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// dom解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//new File(“路径”)
Document root = builder.parse(new File(“resource/book.xml”));
NodeList bookList = root.getElementsByTagName("book");
//↑拿xml的book元素的方法 可返回带有指定名称的所有元素的一个节点列表。
//可以用下列代码检索并遍历 XML文档中的所有 <book> 标记:
System.out.println("bookList" + bookList.getLength());
//↑判断XML有几个book元素
for (int i = 0; i < bookList.getLength(); i++) {
Node node = bookList.item(i);
Element element = (Element) node;// 强转,懂得
System.out.println(“node”+node.getTextContent());//node就相当于拿XML所有数据
// 获取元素的子元素 举栗:<book bid="bk101"><title>红楼梦</title><author>曹雪芹</author></book>
//以bool为父如此就会获得2的长度 title,author为子 空格也算
NodeList sonNodes = node.getChildNodes();
System.out.println("sonNodes" + sonNodes.getLength());
for (int j = 0; j < sonNodes.getLength(); j++) {
Node sonNode = sonNodes.item(j);
if ((sonNode.getNodeType() == 1)) { // 后面就是拿值看看
System.out.println("name:" + sonNode.getNodeName() + ":" + sonNode.getTextContent());
System.out.println("value:" + sonNode.getNodeValue());
System.out.println("Type:" + sonNode.getNodeType());
System.out.println("-----------------");
}
}
System.out.println(sonNodes.getLength());
System.out.println(element.getAttribute("bid") + "\t");
}
}
}