tags:

views:

35

answers:

2

How do I just validate the well-formedness of an XML file in Java?

+1  A: 

You could try "The Java XML Validation API"

http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html

KennyCason
A: 

Just use a validating parser:

import javax.xml.parsers.*;

SAXParserFactory factory=SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser=pf.newSAXParser();

DocumentBuilderFactory has a similar method.

From the JavaDoc:

setValidating

public void setValidating(boolean validating)

Specifies that the parser produced by this code will validate documents as they are parsed. By default the value of this is set to false.

Note that "the validation" here means a validating parser as defined in the XML recommendation. In other words, it essentially just controls the DTD validation. (except the legacy two properties defined in JAXP 1.2.)

To use modern schema languages such as W3C XML Schema or RELAX NG instead of DTD, you can configure your parser to be a non-validating parser by leaving the setValidating(boolean) method false, then use the setSchema(Schema) method to associate a schema to a parser.

Parameters:

    validating - true if the parser produced by this code will validate documents as they are parsed; false otherwise.false otherwise.
Software Monkey