import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.util.Arrays; public class StAXExpand { static XMLStreamWriter xmlsw = null; public static void main(String[] argv) { try { xmlsw = XMLOutputFactory.newInstance() .createXMLStreamWriter(System.out); CompactTokenizer tok = new CompactTokenizer( new FileReader(argv[0])); String rootName = "dummyRoot"; // ignore everything preceding the word before the first "[" while(!tok.nextToken().equals("[")){ rootName=tok.getToken(); } // start creating new document xmlsw.writeStartDocument(); ignorableSpacing(0); xmlsw.writeStartElement(rootName); expand(tok,3); ignorableSpacing(0); xmlsw.writeEndDocument(); xmlsw.flush(); xmlsw.close(); } catch (XMLStreamException e){ System.out.println(e.getMessage()); } catch (IOException ex) { System.out.println("IOException"+ex); ex.printStackTrace(); } } public static void expand(CompactTokenizer tok, int indent) throws IOException,XMLStreamException { tok.skip("["); while(tok.getToken().equals("@")) {// add attributes String attName = tok.nextToken(); tok.nextToken(); xmlsw.writeAttribute(attName,tok.skip("[")); tok.nextToken(); tok.skip("]"); } boolean lastWasElement=true; // for controlling the output of newlines while(!tok.getToken().equals("]")){ // process content String s = tok.getToken().trim(); tok.nextToken(); if(tok.getToken().equals("[")){ if(lastWasElement)ignorableSpacing(indent); xmlsw.writeStartElement(s); expand(tok,indent+3); lastWasElement=true; } else { xmlsw.writeCharacters(s); lastWasElement=false; } } tok.skip("]"); if(lastWasElement)ignorableSpacing(indent-3); xmlsw.writeEndElement(); } private static char[] blanks = "\n".toCharArray(); private static void ignorableSpacing(int nb) throws XMLStreamException { if(nb>blanks.length){// extend the length of space array blanks = new char[nb+1]; blanks[0]='\n'; Arrays.fill(blanks,1,blanks.length,' '); } xmlsw.writeCharacters(blanks, 0, nb+1); } }