ABHILASHA
ABHILASHA

Reputation: 98

How to tell the user that input XML string is invalid without terminating the program in java?

I am reading XML strings from a file and wish to continue reading subsequent strings even if one of those was in invalid format. So how to I continue my program when an incorrect XML string gives a fatal error?

I tried using exception handling but it still gives a fatal error if the XML is not correctly formatted.

Document doc = null;
    try {
        doc = dBuilder.parse(xmlFile);
    }
    catch(Exception e){
        System.out.println(e);
        return;
    }

This is what the console looks like:-

[Fatal Error] IP.xml:22:24: The element type "ValueDate" must be terminated by the matching end-tag "". org.xml.sax.SAXParseException; systemId: file:/D:/Selenium_Workspace/stubvirtualization/IP.xml; lineNumber: 22; columnNumber: 24; The element type "ValueDate" must be terminated by the matching end-tag "".

Upvotes: 0

Views: 480

Answers (1)

second
second

Reputation: 4259

The [Fatal Error] part is just a log message, unrelated to the printing of the exception.

You are not required to do anything, you could just ignore it and move on.


Works fine for me ...

test.xml:

<xml>
<sda
</xml>

main method:

public static void main(String[] args) throws IOException, ParserConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = factory.newDocumentBuilder();

    Document doc = null;
    try {
        doc = dBuilder.parse("test.xml");
    } catch (SAXException e) {
       // do some logging of your own or something
    }

    System.out.println("done");
}

Output on console

[Fatal Error] test.xml:3:1: Element type "sda" must be followed by either attribute specifications, ">" or "/>".
done

Upvotes: 2

Related Questions