I have problems with validating the xml file against xml schema in case when xml document contains schema. The xml file looks like:
<?xml version="1.0"?> <catalog xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:x="urn:book"> <!-- START OF SCHEMA --> <xsd:schema targetNamespace="urn:book"> <xsd:element name="book"> <xsd:complexType> <xsd:sequence> <xsd:element name="author" type="xsd:string"/> <xsd:element name="title" type="xsd:string"/> <xsd:element name="genre" type="xsd:string"/> <xsd:element name="price" type="xsd:float"/> <xsd:element name="publish_date" type="xsd:date"/> <xsd:element name="description" type="xsd:string"/> </xsd:sequence> <xsd:attribute name="id" type="xsd:string"/> </xsd:complexType> </xsd:element> </xsd:schema> <!-- END OF SCHEMA --> <x:book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </x:book> </catalog> java code looks like:
// define the type of schema - we use W3C: String schemaLang = "http://www.w3.org/2001/XMLSchema"; // get validation driver: SchemaFactory factory = SchemaFactory.newInstance(schemaLang); // create schema by reading it from an XSD file: Schema schema = factory.newSchema(new StreamSource("...........")); Validator validator = schema.newValidator(); // at last perform validation: validator.validate(new StreamSource("myDoc.xml")); And the problem for me is how to use SchemaFactory object in this case ?
I'm greatful for any help!
bookas the root element, while your document hascatalogas root element. So basically, you need to split up your document in its two parts, the schema and the contents. There are multiple ways to achieve this; you might use XSL transformations, or work with the document through the DOM API.SchemaFactory.newSchema(StreamSource[]).