XML -对象 读取 遍历 DOM


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 获取 数据值

   

    }

   

   }

    

  }

  

 }

}



转载于:https://my.oschina.net/u/1987177/blog/304672

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值