Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a xml is well formed in java and return all the errors

Tags:

java

xml

I need to check if a given XML is well-formed or not, like if all tags are properly closed or not and there is no junk at the end of the XML. And I also need it to report all errors in the XML. I need to do this validation in java

For example

<Hello>
    <title>Today is a wonderful day </title>
    <car>
        <type>SUV
    <car>
        <type>van</type>
    </car>
</Hello>
</type>
</car>

So the above xml must report the error that there is junk at the end of file and that car and type tags are not closed properly at the given line number

like image 797
harmeet Avatar asked Dec 09 '25 06:12

harmeet


1 Answers

Simply read the file and try to convert it to a DOM. If this does not fail you got a valid XML file.

File fXmlFile = new File("/path/to/my.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
like image 99
BetaRide Avatar answered Dec 10 '25 20:12

BetaRide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!