Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a valid inline XML schema?

I need to author an embedded XML schema, i.e. where the schema is define within the same XML as the data.

I'm trying to understand how to do it correctly, but so far I'm failing to get a simple example to pass validation. Here's what I was trying to use as a trivial example XML with inline schema:
(Note: The XML structure (e.g. root/item) is already out in the wild so I am constrained to not be able to use a namespace on the data elements.)

<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="#mySchema">
  <xs:schema id="mySchema" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="item" type="xs:string"
                      maxOccurs="unbounded" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
   </xs:element>
 </xs:schema>
 <item>String 1</item>
 <item>String 2</item>
 <item>String 3</item>
</root>

But when I run that XML through the w3.org XML Schema Validator, the XML fails validation, with the following error message saying that it wasn't expecting to see <xs:schema> as a child element!

Invalid per cvc-complex-type.1.2.4: element {http://www.w3.org/2001/XMLSchema}:schema not allowed here (1) in element {None}:root, expecting [{None}:item,$]:

Q: Can you show me an example of a simple XML document with inline schema definition that passes validation?

like image 584
Daryn Avatar asked Mar 21 '13 22:03

Daryn


People also ask

What is inline schema in XML?

Inline schemas are a way of including the schema within a WSDL file rather than specifying that it be imported. A schema defines the structure of an XML document. A schema is itself an XML document defined with an xsd extension. There are two ways of including a schema within a WSDL file.

How do I validate an XML file?

XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document.


Video Answer


1 Answers

If your root child has an xs:schema element as a child, then the schema needs to allow it to have such a child. The easiest way to allow it would be to use a wildcard:

<xs:sequence>
  <xs:any processContents="skip" namespace="http://www.w3.org/2001/XMLSchema"
          minOccurs="0" maxOccurs="1"/>
  <xs:element name="item" type="xs:string"
          maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
like image 88
Michael Kay Avatar answered Oct 07 '22 07:10

Michael Kay