Since you do not have an XML schema, there is no reliable way to find the intruder code; for example, XML allows recursive structures. But you CAN write your own XML schema, although this could potentially be a lot to learn. Alternatively, I would create a simple, silly, node-level validator and element name:
private void parseAndCheckStructure(XMLStreamReader reader) throws XMLStreamException { // first read header, this is probably not the offending element (?) int event = -1; while (reader.hasNext()) { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT){ break; } else if (event == XMLStreamConstants.END_DOCUMENT) { throw new XMLStreamException(); } } // read the rest of the document. int level = 1; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT){ level++; String localName = reader.getLocalName(); if(localName.equals("FirstElement")) { parseFirstElementWithALoopLikeTheCurrent(reader); level--; } else if(localName.equals("SecondElement")) { parseSecondElementWithALoopLikeTheCurrent(reader); level--; } else throw new RuntimeException("Unknown element " + localName + " at level " + level + " and location " + reader.getLocation()); } else if(event == XMLStreamConstants.END_ELEMENT) { // keep track of level level--; } } while(level > 0); }
Alternatively, parse the entire document in the above do-while loop and do type checks
if(level == 4 && localName.equals("MyElement")) {
It sucks, but it works.
ThomasRS
source share