Java XMLStreamReader read xml file

Description

Java XMLStreamReader read xml file

import java.io.FileInputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class Main {

   public static void main(String[] args) throws Exception {
      XMLInputFactory factory = XMLInputFactory.newFactory();
      try (FileInputStream fis = new FileInputStream("xmlfile.xml")) {
         XMLStreamReader reader = factory.createXMLStreamReader(fis);
         boolean inName = false;
         boolean inFeature = false;
         String id = null;//from   w  w w .  j av a 2 s .  c  o  m
         String name = null;
         String feature = null;

         while (reader.hasNext()) {
            int event = reader.next();
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
               String elementName = reader.getLocalName();
               switch (elementName) {
               case "language":
                  id = reader.getAttributeValue(0);
                  break;
               case "name":
                  inName = true;
                  break;
               case "feature":
                  inFeature = true;
                  break;
               default:
                  break;
               }
               break;
            case XMLStreamConstants.END_ELEMENT:
               String elementname = reader.getLocalName();
               if (elementname.equals("language")) {
                  System.out.printf("Language: %s\nName: %s\nFeature: %s\n\n", id, name, feature);
                  id = name = feature = null;
                  inName = inFeature = false;
               }
               break;
            case XMLStreamConstants.CHARACTERS:
               if (inName) {
                  name = reader.getText();
                  inName = false;
               } else if (inFeature) {
                  feature = reader.getText();
                  inFeature = false;
               }
               break;
            default:
               break;
            }
         }
         reader.close();
      }
   }
}



PreviousNext

Related