I try to parse unknown xml structure using DOM and get success but now I try to use STAX event or stream parser because of large xml file.Though I do this using SAX and I get success.But now I am little bit curious on STAX.Now I really want to learn about it.
I do some research on that and write this code
This is for STAX streaming
public static void main(String args[]) throws XMLStreamException, FileNotFoundException {
XMLInputFactory xf = XMLInputFactory.newInstance();
XMLStreamReader xsr = xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("c:\\file.xml")));
XMLInputFactoryImpl x = new XMLInputFactoryImpl();
while (xsr.hasNext()) {
int e = xsr.next();
if (e == XMLStreamConstants.START_ELEMENT) {
System.out.println("Element Start Name:" + xsr.getLocalName());
}
if (e == XMLStreamReader.END_ELEMENT) {
System.out.println("Element End Name:" + xsr.getLocalName());
}
if (e == XMLStreamConstants.CHARACTERS) {
System.out.println("Element Text:" + xsr.getText());
}
}
}
And STAX Event driven
public static void main(String[] args) throws XMLStreamException, FileNotFoundException {
// TODO code application logic here
// TODO Auto-generated method stub
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLEventReader xer = xif.createXMLEventReader(new InputStreamReader(new FileInputStream("c:\\file.xml")));
while (xer.hasNext()) {
XMLEvent e = xer.nextEvent();
if (e.isCharacters()) {
System.out.println("Element Text : "+e.asCharacters().getData());
}
if (e.isStartElement()) {
System.out.println("Start Element : "+e.asStartElement().getName());
}
if (e.isEndElement()) {
System.out.println("End Element : "+e.asEndElement().getName());
}
}
}
}
In above two code Parent node also print the blank text but it should not because in xml child node only contains text and it should only print the child node text. for example
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<student id="1">
<fname>TestFirstName</fname>
<lname>TestLastName</lname>
<sectionname rollno="1">A</sectionname>
</student>
It should print TestFirstName,TestLastName etc means it should not return true this lines if (e == XMLStreamConstants.CHARACTERS) or if (e.isCharacters()) for parent nodes to print characters. So how can I modify my code to parse any level of xml file it may be on any depth or any cascading level.