Validating an XML String

From: J. VerSchave (carlisle411_at_yahoo.com)
Date: 02/28/04


Date: 28 Feb 2004 12:00:43 -0800

I am trying to validate some XML. The XML is not in a file. It is
stored in a string. i.e.

String my_xml = "<XML>This is xml</XML>";

I would like to independently verify that my_xml is well formed AND it
is also valid against a specified DTD. This seems easy to do if the
XML were stored in a file or as a URI. However, I currently have the
XML in a string. I could probably write my string to a temp file and
read the file but seems like there should be a cleaner solution. I
was trying to do something like this:

    DefaultHandler handler = new DefaultHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);

    try {

      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse( my_xml, handler );
      MyLogger.info("TextBodyHelper.validateTextBodyXML() - Text is
Valid");
      ...
      ...

Obviously this does not work because saxParser.parse() assumes that
my_xml is a file name and not the XML itself. Does anyone have any
suggestions? Examples? URLs? Thanks.

-j



Relevant Pages