栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java如何解析/读取xml文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java如何解析/读取xml文件

本文实例为大家分享了java解析/读取xml文件的方法,供大家参考,具体内容如下

XML文件

 
 
   
    John 
    B 
    12 
   
   
    Mary 
    A 
    11 
   
   
    Simon 
    A 
    18 
   

Java 代码:

package net.viralpatel.java.xmlparser;  
  
import java.io.File;  
import javax.xml.parsers.documentBuilder;  
import javax.xml.parsers.documentBuilderFactory;  
  
import org.w3c.dom.document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
  
public class XMLParser {  
  
  public void getAllUserNames(String fileName) {  
    try {  
      documentBuilderFactory dbf = documentBuilderFactory.newInstance();  
      documentBuilder db = dbf.newdocumentBuilder();  
      File file = new File(fileName);  
      if (file.exists()) {  
 document doc = db.parse(file);  
 Element docEle = doc.getdocumentElement();  
  
 // Print root element of the document  
 System.out.println("Root element of the document: " 
     + docEle.getNodeName());  
  
 NodeList studentList = docEle.getElementsByTagName("student");  
  
 // Print total student elements in document  
 System.out  
     .println("Total students: " + studentList.getLength());  
  
 if (studentList != null && studentList.getLength() > 0) {  
   for (int i = 0; i < studentList.getLength(); i++) {  
  
     Node node = studentList.item(i);  
  
     if (node.getNodeType() == Node.ELEMENT_NODE) {  
  
System.out  
    .println("=====================");  
  
Element e = (Element) node;  
NodeList nodeList = e.getElementsByTagName("name");  
System.out.println("Name: " 
    + nodeList.item(0).getChildNodes().item(0)  
 .getNodevalue());  
  
nodeList = e.getElementsByTagName("grade");  
System.out.println("Grade: " 
    + nodeList.item(0).getChildNodes().item(0)  
 .getNodevalue());  
  
nodeList = e.getElementsByTagName("age");  
System.out.println("Age: " 
    + nodeList.item(0).getChildNodes().item(0)  
 .getNodevalue());  
     }  
   }  
 } else {  
   System.exit(1);  
 }  
      }  
    } catch (Exception e) {  
      System.out.println(e);  
    }  
  }  
  public static void main(String[] args) {  
  
    XMLParser parser = new XMLParser();  
    parser.getAllUserNames("c:\test.xml");  
  }  
} 

以上就是本文的全部内容,希望对大家的学习有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150414.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号