CSharp - Obtaining an XML Schema

Introduction

Creating an XSD Schema by Inferring It from an XML Document

In the following code, we first create our typical XML document.

Next, we instantiate an XmlSchemaInference object and create an XmlSchemaSet by calling the InferSchema method on the XmlSchemaInference object.

We create a writer and enumerate through the set of schemas, writing each to the bookparticipants.xsd file.

Last, we load in the generated XSD schema file and display it.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;

class Program//from  w w  w  .ja  v  a 2 s. c om
{
    static void Main(string[] args){
          XDocument xDocument = new XDocument(
        new XElement("Books",
          new XElement("Book",
            new XAttribute("type", "Author"),
            new XElement("FirstName", "Joe"),
            new XElement("LastName", "Ruby")),
          new XElement("Book",
            new XAttribute("type", "Editor"),
            new XElement("FirstName", "PHP"),
            new XElement("LastName", "Python"))));

      Console.WriteLine("Here is the source XML document:");
      Console.WriteLine("{0}{1}{1}", xDocument, System.Environment.NewLine);

      xDocument.Save("bookparticipants.xml");

      XmlSchemaInference infer = new XmlSchemaInference();
      XmlSchemaSet schemaSet =
        infer.InferSchema(new XmlTextReader("bookparticipants.xml"));

      XmlWriter w = XmlWriter.Create("bookparticipants.xsd");
      foreach (XmlSchema schema in schemaSet.Schemas())
      {
        schema.Write(w);
      }
      w.Close();

        XDocument newDocument = XDocument.Load("bookparticipants.xsd");
        Console.WriteLine("Here is the schema:");
        Console.WriteLine("{0}{1}{1}", newDocument, System.Environment.NewLine);

    }
}

Result

Related Topics