且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

利用java读取xml节点数据

更新时间:2022-08-13 08:18:07

xml叫可扩展标记语言 和html的区别在于 显示层和 数据层分离  。

显示可以用css或者  xsl设置数据的显示格式 

利用java对xml文件进行解析 用到的类  DocumentBuilderFactory  xml解析器工具   DocumentBuilder文档解析器    Document文档类  NodeList节点类

package me.dom.test;
import javax.xml.parsers.*;    //导入相关类
import org.w3c.dom.*;   
import org.w3c.dom.NodeList;  //导入DOM节点类
import java.io.*;   //io包
public class DomTest

 
 public static void main(String []args)  throws Exception   
 {
  
  DocumentBuilderFactory buf=DocumentBuilderFactory.newInstance() ;   //xm解析器生成工具  的静态方法  直接生成xml解析器
  DocumentBuilder db=buf.newDocumentBuilder()  ;  //xml解析器工具来生成一个xml解析器对象 因为 DocumentBuilder没有提供共有构造方法
  Document dom= db.parse(new File("C:\\Users\\xiaowei\\Desktop\\idnex.xml")) ;    //将一个xml文件转换成一个DOM对象  也就是Document 
  NodeList list=dom.getElementsByTagName("name")  ;//返回节点对象
  for(int i=0;i<list.getLength();i++)  
  {
   System.out.println(list.item(i).getTextContent());  //循环输出 节点文本
  }
    
  
  
 }

}