1

Following this tutorial I was able to create an XML file and following this tutorial I was able to parse the XML file

I now want know how to check if the xml is a valid format before adding another Staff, if the xml is malformed it will exit out and give an error that it can't parse.

If it parses a gibberish file such as this, it will exit and not continue

asdsadasfsadf

If it parses a valid XML but not in the correct format, it will exit also (the first node is root instead of company)

<root>
<staff id="1001">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>100000</salary>
</staff>
<staff id="2001">
    <firstname>low</firstname>
    <lastname>yin fong</lastname>
    <nickname>fong fong</nickname>
    <salary>200000</salary>
</staff>
</root>    
  • Welcome to Stack Overflow! Please take the [tour](http://stackoverflow.com/tour), have a look around, and read through the [help center](http://stackoverflow.com/help), in particular [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) and [What topics can I ask about here?](http://stackoverflow.com/help/on-topic). – Timothy Truckle Jul 18 '17 at 09:19
  • 1
    define a XSD, let JABX (or any other XML framework) generate mapper classes and configure the *unmarshaller* to check validity of the document on load. – Timothy Truckle Jul 18 '17 at 09:20
  • Read about : [JAXB](https://docs.oracle.com/javase/tutorial/jaxb/intro/) – Frank Jul 18 '17 at 09:22
  • @Thenikedestroyer check out his question https://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file#16054 – noscreenname Jul 18 '17 at 09:23

1 Answers1

1

Basically there are two things you are trying to achieve: check to see if your xml is well formed, and check to see if it is valid (valid xml conforms to a DTD or XSD).

To check to see if is well formed, you can just simply try and parse it with any major xml parser, it will throw an exception of it is not well formed.

To check to see if it is valid, validate it against a schema (I would recommend using an XSD and not DTD but that is just me) there are many ways to do this, a few are mentioned here What's the best way to validate an XML file against an XSD file?

Additionally if you validate your xml against a schema you will also be checking that it is well formed, because only well formed xml can be validated.

MartinByers
  • 1,240
  • 1
  • 9
  • 15