public class DocumentBuilderTest {
public static void main(String[] args) throws Exception {
/* //要获取 XML 文件 对象 导入 对象 --》 DocumentBuilderFactory - instance new DocumentBuilder
//获取DB工厂 对象
DocumentBuilderFactory dbBuilder = DocumentBuilderFactory.newInstance();
//通过 DB 工厂 获取 DB 对象 newDocumentBuilder();
DocumentBuilder Dbuilder= dbBuilder.newDocumentBuilder();
// 通过 DB 对象 获取 xml 文件 Document对象
Document document =Dbuilder.parse("src/book.xml");
// Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// System.out.println(document);
*/
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("src/book.xml");
//System.out.println(document);
//取出 想要的所有数据 -- 要从 根节点的 下一级 取出 nodeList 是 节点 集合 --
NodeList nodeList= document.getElementsByTagName("book");
//System.out.println(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
//获取 节点
Node b = nodeList.item(i);
//b 对象 明确是一个 element - 多态给 Node 接口 没什么功能可用的 需要 向下转型
Element book = (Element)b;
if(book.hasAttributes())
{
System.out.println(book.getAttribute("id"));
}
//获取book child 节点
NodeList childNodes = book.getChildNodes();
//System.out.println(childNodes.getLength());
for (int j = 0; j < childNodes.getLength(); j++) {
//取出 book child 集合中 的一个元素
Node node = childNodes.item(j);
//筛选 元素 -- 把text 元素 忽略 // getNodeType getNodeType
if(node.ELEMENT_NODE== node.getNodeType()){
//强转 取数
Element childNode = (Element)node;
//String value = childNode.getTextContent();// 最外层的 元素节点 后面挂 叶子的可以直接获取 叶子字符串
// System.out.println(value);
//获取叶子节点 文本对象 --get 出来的 对象都是 NODE 类型的
Text text = (Text)childNode.getFirstChild();
System.out.println(text.getData()); //叶子 的 文本节点 使用 getData 获取 数据值
}
}
}
}
}