Creating XML Schema from XML documents/elements

We often use schema to validate XML documents. However, there are times when there’s no schema available for existing XML data. I found out just recently that .NET framework can actually do this for me! So this is another “Oh..I didn’t know I can do that” post.

The key here is to use System.Xml.Schema.XmlSchemaInference class.

using XMLSchemaInference

Using XMLSchemaInference to retrieve XSD schema from existing XML content

As you can see from this code, you can get schema by simply call InterSchema method with XMLReader as parameter. The XMLReader parameter should contain the XML document/fragments that you want to generate schema for.

I created an XML utility from the code above. Try running the application with this example data.

The output schema looks like this

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Items">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="Item">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Price" type="xs:decimal" />
</xs:sequence>
<xs:attribute name="id" type="xs:unsignedShort" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="year" type="xs:unsignedShort" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>

The more specific XML data given, the more detailed schema is generated. Letting the framework generate schema should not be the end solution, it merely gives you a rough draft for the schema that you can then add and refine later.

 

 

Teera on June 24th 2008 in Software Development, .NET

Trackback URI | Comments RSS

Leave a Reply