Validating an XML String

J

J. VerSchave

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
 
B

Barry White

I haven't got the SAX api docs in front of me but I'd be suprised if it
restricts you to only files and not something more abstract like an
InputStream.

If that's the case you could try a StringBufferInputStream or
ByteArrayInputStream. Byte array might be better as you could specify
the encoding as follows (encoding will be important for an xml parser):

String xmlString = ....;
ByteArrayInputStream in =
new ByteArrayInputStream(xmlString.getBytes("iso-8859-1"));

...create SAX parser with specified encoding.

Barry
 
B

Barry White

My curiousity got the better of me...

SAXParser saxParser = factory.newSAXParser();
StringReader reader = new StringReader(xmlString);
InputSource source = new InputSource(reader);
saxParser.parse(source, handler);
 
S

Sudsy

J. VerSchave said:
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>";
<snip>

Reader rdr = new StringReader( my_xml );

You should then be able to coerce it into a form (such as InputSource)
which is acceptable to your parser, e.g. like this:

saxParser.parse( new InputSource( rdr ), handler );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top