>

Vaibhav's Blog Space

XML Event in JDK6

Thursday Jul 03, 2008

Java SE 6, added the new class XMLEvent in the package javax. xml. stream.events. This is the base event interface for handling markup events. Not only that,  Events may be cached and referenced after the parse has completed.

I have simply tried to write a code which can find the skeleton of my XML file and show me only tag structure. 10 lines of code is enough to do this job. And with the strong API of XMLEvent , you can play with thousands of things in a XML file.

Here is my XML file(taken somewhere from Internet):

 <recipe name="bread" prep_time="5 mins" cook_time="3 hours">
<!-- this is comment section -->
   <title>Basic bread</title>
   <ingredient amount="8" unit="dL">Flour</ingredient>
   <ingredient amount="10" unit="grams">Yeast</ingredient>
   <ingredient amount="4" unit="dL" state="warm">Water</ingredient>
   <ingredient amount="1" unit="teaspoon">Salt</ingredient>
   <instructions>
     <step>Mix all ingredients together.</step>
     <step>Knead thoroughly.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Knead again.</step>
     <step>Place in a bread baking tin.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Bake in the oven at 180(degrees)C for 30 minutes.</step>
   </instructions>
 </recipe>

And here is the small code, helped me to find out the tag structure.

import java.io.FileInputStream;
import javax.xml.stream.*;
import javax.xml.stream.events.*;

public class EventParse {
    public static void main(String[] args) throws Exception {

        String filename = "hello.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader xmler = factory.createXMLEventReader(filename,new FileInputStream(filename));
        System.out.println("Skeleton of XML file:");
        while (xmler.hasNext()) {
            XMLEvent e = xmler.nextEvent();
                 if(e.getEventType()==1) {
                    System.out.println(e.toString());
                    }        
                  if(e.getEventType()==2) {
                    System.out.println(e.toString());
 
                    }
    }
   }
}

and the output:

<recipe cook_time='3 hours' name='bread' prep_time='5 mins'>
<title>
</title>
<ingredient amount='8' unit='dL'>
</ingredient>
<ingredient amount='10' unit='grams'>
</ingredient>
<ingredient amount='4' unit='dL' state='warm'>
</ingredient>
<ingredient amount='1' unit='teaspoon'>
</ingredient>
<instructions>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
<step>
</step>
</instructions>
</recipe>

[6] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg