当前位置: 移动技术网 > IT编程>开发语言>Java > java遍历读取xml文件内容

java遍历读取xml文件内容

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲解了java遍历读取xml文件内容的详细代码,分享给大家供大家参考,具体内容如下

package test;
 
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.util.iterator;
 
import javax.xml.namespace.namespacecontext;
import javax.xml.namespace.qname;
import javax.xml.stream.xmlinputfactory;
import javax.xml.stream.xmloutputfactory;
import javax.xml.stream.xmlstreamexception;
import javax.xml.stream.xmlstreamreader;
import javax.xml.stream.xmlstreamwriter;
 
import org.apache.axiom.om.omabstractfactory;
import org.apache.axiom.om.omattribute;
import org.apache.axiom.om.omcomment;
import org.apache.axiom.om.omcontainer;
import org.apache.axiom.om.omdatasource;
import org.apache.axiom.om.omdoctype;
import org.apache.axiom.om.omdocument;
import org.apache.axiom.om.omelement;
import org.apache.axiom.om.omexception;
import org.apache.axiom.om.omfactory;
import org.apache.axiom.om.omnamespace;
import org.apache.axiom.om.omprocessinginstruction;
import org.apache.axiom.om.omsourcedelement;
import org.apache.axiom.om.omtext;
import org.apache.axiom.om.omxmlparserwrapper;
import org.apache.axiom.om.impl.builder.staxombuilder;
import org.xml.sax.helpers.xmlreaderfactory;
 
public class axiomtest {
 public static void main(string[] args) throws filenotfoundexception, throwable {
//  read xml
    fileinputstream xmlfile = new fileinputstream("line-item2.xml");
    xmlstreamreader parser = xmlinputfactory.newinstance().createxmlstreamreader(xmlfile);
 
    // 还需要staxombuilder对象
    staxombuilder builder = new staxombuilder(parser);
    
    omelement doc = builder.getdocumentelement();   //  读到<fool></fool>    
    
    omelement cre = doc.getfirstchildwithname(new qname("student")); //读到<student>
    
    omelement cre1 = cre.getfirstchildwithname(new qname("id")); //  读到<id></id>
    system.out.println(cre1.getlocalname()+":"+cre1.gettext());
    cre1 = cre.getfirstchildwithname(new qname("name"));    //  读到<name></name>
    system.out.println(cre1.getlocalname()+":"+cre1.gettext()); 
   
    cre1 = cre.getfirstchildwithname(new qname("age"));   //  读到<age></age>
    system.out.println(cre1.getlocalname()+":"+cre1.gettext());  
    
    cre1 = cre.getfirstchildwithname(new qname("sex"));   //  读到<sex></sex>
    system.out.println(cre1.getlocalname()+":"+cre1.gettext());
    
    cre1 = cre.getfirstchildwithname(new qname("message"));   //  读到<sex></sex>
    system.out.println(cre1.getlocalname()+":"+cre1.gettext());
    
    system.out.println("------------------------------1");
    iterator<omelement> iter = doc.getchildelements();
    while(iter.hasnext()){
      omelement temp = iter.next();
      system.out.println("====================");
      system.out.println(temp.getlocalname());
//      system.out.println(temp.gettext());
 
      if(temp.getlocalname().equals("student")){
        iterator<omelement> iter1 = temp.getchildelements();
        system.out.println("----------------");
        while(iter1.hasnext()){
          omelement temp1 = iter1.next();          
          system.out.println(temp1.getlocalname()+":"+temp1.gettext());
        }
      }
    }
    system.out.println("!!!!!!!!!!!!!");
    fileinputstream file = new fileinputstream("line-item2.xml");
    xmlstreamreader read = xmlinputfactory.newinstance().createxmlstreamreader(file);
    staxombuilder sta = new staxombuilder(read);
    omelement all = sta.getdocumentelement();
    iterator<omelement> ite1 = all.getchildelements();
    while(ite1.hasnext()){
      omelement temp = ite1.next();
      if(temp.getlocalname().equals("student")){
       iterator<omelement> ite2 = temp.getchildelements();
       while(ite2.hasnext()){
         omelement temp1 = ite2.next();
         system.out.println(temp1.getlocalname()+":"+temp1.gettext());
      }     
    }
   }    
//    write xml
    
    omfactory factory = omabstractfactory.getomfactory();
    
    //建立doc节点,doc节点会和下面的root节点合并
    omdocument dod = factory.createomdocument();
    
    //建立root节点
    omelement root = factory.createomelement("root","","");
    omelement add = factory.createomelement("dabi","","");
    //建立两个普通节点
    omelement stu = factory.createomelement("student","","");
    stu.addchild(factory.createomtext("mac"));
 
    omelement tea = factory.createomelement("teacher","","");
    tea.addchild(factory.createomtext("silly"));
    
    //构建树,将两个普通节点连到root节点上
    root.addchild(stu);
    root.addchild(tea);
    //构建树,将root节点连到doc节点上
    dod.addchild(root);
    
    // 构建writer做输出器
    xmlstreamwriter writer = xmloutputfactory.newinstance().createxmlstreamwriter(
        new fileoutputstream("2.xml"));
    root.serialize(writer); // cache on
    writer.flush();
    
    fileinputstream xmlfile1 = new fileinputstream("2.xml");
    xmlstreamreader parser1 = xmlinputfactory.newinstance().createxmlstreamreader(xmlfile1);
    
    staxombuilder builder1 = new staxombuilder(parser1);
    omelement doc1 = builder1.getdocumentelement();
    
    iterator<omelement> iter1 = doc1.getchildelements();
    while(iter1.hasnext()){
      omelement temp = iter1.next();
      system.out.println("====================");
      system.out.println(temp.getlocalname()+":"+temp.gettext());
    }
 
    
    system.out.println("!!!!!!!!");
 
    omfactory omf = omabstractfactory.getomfactory();
//    omdocument od = omf.createomdocument();
    omelement root1 = omf.createomelement("root","","");
    omelement name = omf.createomelement("name","","");
    omelement sex = omf.createomelement("sexy","","");
    sex.addchild(omf.createomtext("man"));
    name.addchild(omf.createomtext("dabi"));
    root1.addchild(sex);
    root1.addchild(name);
//    od.addchild(root1);
    
    xmlstreamwriter xmlw = xmloutputfactory.newinstance().createxmlstreamwriter(new fileoutputstream("3.xml"));
    root1.serialize(xmlw);
    
    xmlw.flush();
 }
}
<?xml version="1.0" encoding="utf-8"?>
<fool>
  <student>
    <name>mac</name>
    <id>12</id>
    <age>33</age>
    <sex>male</sex>
    <message>hello world</message>
  </student>
  <student>
    <name>silly</name>
    <id>5</id>
    <age>12</age>
    <sex>female</sex>
  </student>
  <teacher>
    <name>mr. jones</name>
    <id>2</id>
    <age>31</age>
    <sex>male</sex>
  </teacher>
  <student>
    <name>macy</name>
    <id>2</id>
    <age>40</age>
    <sex>female</sex>
  </student>
  <student>
    <name>tom</name>
    <id>32</id>
    <age>31</age>
    <sex>male</sex>
  </student>
  <message>hello world</message>
</fool>

再分享一例: 用java读取xml文件

解析xml的步骤如下:

  •   1.创建documentbuilder工厂
  •   2.创建documentbuilder对象
  •   3.documentbuilder对象的parse方法得到document对象
  •   4.document对象的getelementsbytagname得到nodelist集合
  •   5.通过getfirstchild和getnextsibling进行遍历 

用到的包:

  • import javax.xml.parsers.*;
  • import org.w3c.dom.*;
  • import org.xml.sax.*;

用到的对象:

  • documentbuilderfactory:创建documentbuilder的抽象工厂
  • documentbuilder:可以从 xml 获取一个 document
  • document:提供供对文档数据的基本访问

用到的方法:

  • documentbuilder.parse(string)':将给定 uri 的内容解析为一个 xml 文档,并且返回一个新的 dom document对象
  • document.getelementsbytagname(string)':返回具有给定标记名称的所有 element 的 nodelist
  • element.getattribute(string)':通过名称获得属性值

下面来解析一个xml文件

import javax.xml.parsers.*; 
import org.w3c.dom.*; 
import org.xml.sax.*; 
 
public class test 
{ 
  public static void main(string[] args) 
  { 
    documentbuilderfactory dbf = documentbuilderfactory.newinstance(); 
    try 
    { 
      documentbuilder db = dbf.newdocumentbuilder(); 
      document doc = db.parse("pet2.xml"); 
 
      nodelist doglist = doc.getelementsbytagname("dog"); 
      system.out.println("共有" + doglist.getlength() + "个dog节点"); 
      for (int i = 0; i < doglist.getlength(); i++) 
      { 
        node dog = doglist.item(i); 
        element elem = (element) dog; 
        system.out.println("id:" + elem.getattribute("id")); 
        for (node node = dog.getfirstchild(); node != null; node = node.getnextsibling()) 
        { 
          if (node.getnodetype() == node.element_node) 
          { 
            string name = node.getnodename(); 
            string value = node.getfirstchild().getnodevalue(); 
            system.out.print(name + ":" + value + "\t"); 
          } 
        } 
        system.out.println(); 
      } 
    } 
    catch (exception e) 
    { 
      e.printstacktrace(); 
    } 
  } 
} 

xml文件

<pets> 
  <dogs> 
    <dog id="1">      
      <name>yaya</name> 
      <health>100</health> 
      <love>0</love> 
      <strain>酷酷的雪娜瑞</strain> 
    </dog> 
    <dog id="2">      
      <name>ouou</name> 
      <health>90</health> 
      <love>15</love> 
      <strain>聪明的拉布拉多犬</strain> 
    </dog> 
  </dogs> 
  <penguins> 
    <penguin id="3">      
      <name>qq</name> 
      <health>100</health> 
      <love>20</love> 
      <sex>q仔</sex>       
    </penguin>     
  </penguins> 
</pets> 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网