Search code examples
javaxmlxml-parsingstaxwell-formed

StAX well-formedness check of XML


I am checking an XML document for well formedness (only syntax check). I am not validating against any schema. I need to do this using StAX:

I do know that I have to parse the file, but how do I implement the check?

XMLInputFactory factory = XMLInputFactory.newInstance(); 
File f = new File(uploadfileName);
FileInputStream inputStream = new FileInputStream(f); 
//Instantiate a reader parsing:
XMLStreamReader reader=factory.createXMLStreamReader(inputStream);

        while(reader.hasNext()){
            //check to be implemented??
            reader.next();
        }

Solution

  • As @Andreas commented, well-formedness will be indicated by the lack of any exception being thrown in the course of consuming all parsing events.

    Specifically, XMLStreamReader.next() will throw a XMLStreamException for any well-formedness errors encountered in the XML being parsed. If parsing progresses to where XMLStreamReader.hasNext() returns false and terminates your while loop without having triggered any XMLStreamExceptions, you can be sure that the XML is well-formed.