Creating an XSD Schema by Inferring Itfrom an XML Document

   
 

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XDocument xDocument = new XDocument(
          new XElement("Books",
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "A"),
              new XElement("LastName", "B")),
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "C"),
              new XElement("LastName", "D"))));

        Console.WriteLine(xDocument);
        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(newDocument);
    }
}

    


This entry was posted in XML LINQ. Bookmark the permalink.