JAva遍歴xmlファイル内容の読み出し

11092 ワード

本文の例は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();   //        
    
    OMElement cre = doc.getFirstChildWithName(new QName("student")); //  
    
    OMElement cre1 = cre.getFirstChildWithName(new QName("id")); //    
    System.out.println(cre1.getLocalName()+":"+cre1.getText());
    cre1 = cre.getFirstChildWithName(new QName("name"));    //    
    System.out.println(cre1.getLocalName()+":"+cre1.getText()); 
   
    cre1 = cre.getFirstChildWithName(new QName("age"));   //    
    System.out.println(cre1.getLocalName()+":"+cre1.getText());  
    
    cre1 = cre.getFirstChildWithName(new QName("sex"));   //    
    System.out.println(cre1.getLocalName()+":"+cre1.getText());
    
    cre1 = cre.getFirstChildWithName(new QName("message"));   //    
    System.out.println(cre1.getLocalName()+":"+cre1.getText());
    
    System.out.println("------------------------------1");
    Iterator 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 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 ite1 = all.getChildElements();
    while(ite1.hasNext()){
      OMElement temp = ite1.next();
      if(temp.getLocalName().equals("student")){
       Iterator 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 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();
 }
}



  
    mac
    12
    33
    male
    hello world
  
  
    silly
    5
    12
    female
  
  
    Mr. Jones
    2
    31
    male
  
  
    macy
    2
    40
    female
  
  
    tom
    32
    31
    male
  
  hello world



再共有一例:XMLファイルをJAVAで読み込む
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ファイル
    
     
       
              
          YAYA 
          100 
          0 
                 
         
              
          OUOU 
          90 
          15 
                   
         
       
       
              
          QQ 
          100 
          20 
          Q        
             
       
     

    以上が本文のすべての内容で、みんなの学習に役立つことを望みます.