File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
I/O and Streams
Validate XML from a string instead of a file?
Joined: Feb 09, 2010
Feb 09, 2010 13:10:02
I have XML that is saved in the
format, and I need to validate it against an XSD file. I know how to do it using an XML
+ XSD file, but how is it done with a String and an XSD file? thanks for the help
Joined: Feb 09, 2010
Feb 09, 2010 13:27:58
I am not sure what parse you want to use. But all the XML parsers API's will support "string" type as well. Below is just an example. You need to look at the API of the parser of you are using.
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema myschema=schemaFactory.newSchema(new File("./temp/myxsd.xsd"); DocumentBuilderFactory domParserFactory = DocumentBuilderFactory.newInstance(); domParserFactory.setValidating(true); domParserFactory.setSchema(myschema); DocumentBuilder builder = domParserFactory.newDocumentBuilder(); builder.parse(new File("./temp/myxml.xml");
Joined: Oct 14, 2005
Feb 09, 2010 13:40:21
Actually that's an example of how to parse XML from a file. To parse from a string using that same parser:
String xmlString = // some string containing an XML document builder.parse(new InputSource(new StringReader(xmlString)));
Joined: Jan 13, 2010
Feb 09, 2010 16:22:19
You can try this:
StringReader reader = new StringReader(yourXML); URL xsdResource = ValidarXML.class.getClassLoader().getResource("yourXSD.xsd"); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = factory.newSchema(xsdResource); Validator val = schema.newValidator(); val.validate(new StreamSource(reader));
i think that xerces is requeried
It is sorta covered in the
JavaRanch Style Guide
subject: Validate XML from a string instead of a file?
How look at DOM element in XML (with backing Schema) and determine it's type, etc?
XML Schema Help
how to validate xml document with xml schema in netbean and how to create simpleType in Netbean
XML validation against XSD
validating xml with xsd
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014