Sunday, December 7, 2008

STAX - Parse an XML Doc and print out all the attributes of that element

This might be useful for anyone looking for a simple example for Stax - this will run through a locally saved xml file and write out the element and all its attributes:


import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class BasicStax {
public static void main(String[] args){


try {
XMLInputFactory factory = XMLInputFactory.newInstance();

XMLStreamReader reader =
factory.createXMLStreamReader(new FileReader("xmlfile.xml"));

while (reader.hasNext())
{
if (reader.isStartElement())
{

System.out.println("Start Element: " + reader.getName());
for(int i = 0, n = reader.getAttributeCount(); i < n; ++i) {
System.out.println("Attribute: " + reader.getAttributeName(i)
+ "=" + reader.getAttributeValue(i));
}
System.out.println("=============================");

}
reader.next();
}
reader.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}
}

0 comments:

Blog Archive

About Me