Java traversal reads XML file content _java

Source: Internet
Author: User

This article explains the Java traversal read XML file content of the detailed code, share for everyone to refer to, the specific content as follows

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);
    
    Also need Staxombuilder object Staxombuilder builder = new Staxombuilder (parser);   Omelement doc = Builder.getdocumentelement (); Read <fool></fool> omelement cre = doc.getfirstchildwithname (new QName ("Student")); Read <student> omelement cre1 = cre.getfirstchildwithname (new QName ("id"));
    Read <id></id> System.out.println (cre1.getlocalname () + ":" +cre1.gettext ());    Cre1 = Cre.getfirstchildwithname (new QName ("name")); Read the <nam.E></name> System.out.println (Cre1.getlocalname () + ":" +cre1.gettext ());   Cre1 = Cre.getfirstchildwithname (New QName ("Age"));  
    
    Read <age></age> System.out.println (cre1.getlocalname () + ":" +cre1.gettext ());   Cre1 = Cre.getfirstchildwithname (new QName ("Sex"));
    
    Read <sex></sex> System.out.println (cre1.getlocalname () + ":" +cre1.gettext ());   Cre1 = Cre.getfirstchildwithname (New QName ("message"));
    
    Read <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 ();
    
    Establish a Doc node, the doc node will merge with the root node below omdocument DoD = Factory.createomdocument ();
    Establish root node omelement root = factory.createomelement ("root", "", "");
    Omelement add = factory.createomelement ("Dabi", "", "");
    Establish two common nodes omelement stu = factory.createomelement ("Student", "", "");
 
    Stu.addchild (Factory.createomtext ("Mac"));
    Omelement tea = factory.createomelement ("Teacher", "", "");
    
    Tea.addchild (Factory.createomtext ("silly"));
    Constructs the tree, connects two common nodes to the root node Root.addchild (STU);
    Root.addchild (tea);
    
    Build the tree, connecting the root node to the Doc node dod.addchild (root); Build writer to do the output xmlstreamwriter writer = Xmloutputfactory.newinstance (). Createxmlstreamwriter (New fileoutputs
    Tream ("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> &LT;ID&G t;12</id> <age>33</age> <sex>male</sex> <message>hello WORLD&LT;/MESSAGE&G
  T </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</ag

 e> <sex>male</sex> </student> <message>hello world</message> </fool>

Another example: reading XML files in Java

The steps for parsing XML are as follows:

    • 1. Create Documentbuilder Factory
    • 2. Create a Documentbuilder object
    • The parse method of 3.DocumentBuilder object gets the Document object
    • getElementsByTagName of 4.Document objects gets nodelist collection
    • 5. Traverse through Getfirstchild and getnextsibling

Packages used:

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

Objects to use:

    • Documentbuilderfactory: Creating a Documentbuilder abstract factory
    • Documentbuilder: You can get a Document from XML
    • Document: Provides basic access to documentation data

The method used:

    • Documentbuilder.parse (String): resolves the contents of a given URI into an XML document and returns a new DOM Document object
    • document.getElementsByTagName (String) ': Returns the nodelist of all the Element with the given tag name
    • Element.getattribute (String) ': Get property value by name

The following resolves an XML file

Import javax.xml.parsers.*; 
Import org.w3c.dom.*; 
 
Import org.xml.sax.*; public class Test {public static void main (string[] args) {documentbuilderfactory dbf = Documentbuilderfacto 
    Ry.newinstance (); 
      try {Documentbuilder db = Dbf.newdocumentbuilder (); 
 
      Document doc = Db.parse ("Pet2.xml"); 
      NodeList doglist = Doc.getelementsbytagname ("dog"); 
      SYSTEM.OUT.PRINTLN ("Total" + doglist.getlength () + "Dog Node"); 
        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.getnodety 
            PE () = = 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 file

<pets> 
  <dogs> 
    <dog id= "1" >      
      <name>YAYA</name> 
       
 

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.