欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java如何解析/读取xml文件

程序员文章站 2024-03-08 23:58:40
本文实例为大家分享了java解析/读取xml文件的方法,供大家参考,具体内容如下 xml文件

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

xml文件

<?xml version="1.0"?> 
<students> 
  <student> 
    <name>john</name> 
    <grade>b</grade> 
    <age>12</age> 
  </student> 
  <student> 
    <name>mary</name> 
    <grade>a</grade> 
    <age>11</age> 
  </student> 
  <student> 
    <name>simon</name> 
    <grade>a</grade> 
    <age>18</age> 
  </student> 
</students>

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");  
  }  
} 

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