Checking to see if xml is well-formed in my servlet code

Hi,

I am grabbing content from a database, this content is *supposed* to be well-formed xml but as this is user-input I need to validate it before I send it back to the browser, is there simple code that I can use to validate the content I have as well-formed xml before sending it to the browser?

Thanks.

[324 byte] By [nemcovaa] at [2007-11-26 21:06:17]
# 1
Just validate the xml against its Schema or DTD.
bckrispia at 2007-7-10 2:40:16 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...
# 2
Or if it doesn't have a schema or DTD, and you just want to know if it's well-formed, then create a SAXParser and parse it. If that throws an exception then it's not well-formed.
DrClapa at 2007-7-10 2:40:16 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...
# 3

Found a good way of doing it in java code:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder db = dbf.newDocumentBuilder();

StringReader reader = new StringReader(testValue);

InputSource source = new InputSource(reader);

Document dom = db.parse(source);}

catch(Exception e) {compliant = 0;}

nemcovaa at 2007-7-10 2:40:16 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...
# 4
^ A SAX parser would be more lightweight than DOM for this job.
bckrispia at 2007-7-10 2:40:16 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...