harmeet
harmeet

Reputation: 57

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

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

Upvotes: 3

Views: 17995

Answers (2)

Cristian Marian
Cristian Marian

Reputation: 780

Basically you want to get all the errors a xml code has.

What you are trying to do is a bit tricky without a schema. Consider this code:

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

This code is a valid xml code but I guess that it's hardly what you want. So, trying to validate the code with parsers without a schema will do you no good.

If you don't want to use a schema, you could use a stack (having in mind the layout)and validate the code by adding/removing to/from the stack the begining and ending tags.

Upvotes: -2

BetaRide
BetaRide

Reputation: 16844

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);

Upvotes: 12

Related Questions