someName
someName

Reputation: 1273

How do I dynamically create an XML schema in C#?

I try to dynamically create an XML schema (XSD) from C#, using the conventional XElement and XAttribute classes, but it is not valid to specify any names with colons. That is, I cannot create the element <xs:element> using the code

... = new XElement("xs:element");

because ":" is not allowed.

What is the correct way of dynamically building a schema in C# then?

Upvotes: 2

Views: 7848

Answers (4)

code4life
code4life

Reputation: 15794

To create schemas, you should be using the XmlSchema class. The link below provides a comprehensive example of creating one programmatically:

http://msdn.microsoft.com/en-us/library/9ta3w88s.aspx


Example:

static void Main(string[] args)
{
    var schema = new XmlSchema();

    // <xs:element name="myElement" type="xs:string"/>
    var myElement = new XmlSchemaElement();
    schema.Items.Add(myElement);
    elementCat.Name = "myElement";
    elementCat.SchemaTypeName = 
        new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

    // writing it out to any stream
    var nsmgr = new XmlNamespaceManager(new NameTable());
    nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
    schema.Write(Console.Out, nsmgr);

    Console.ReadLine();
}

Upvotes: 2

Matt DeKrey
Matt DeKrey

Reputation: 11932

When creating new XML elements, you should be aware that the part before the colon (in this case, xs) is actually an alias for the XML namespace (in the case of an XSD, xs usually refers to http://www.w3.org/2001/XMLSchema). So, to continue using XDocument to build your XSD, you would want to use:

XNamespace ns = new XNamespace("http://www.w3.org/2001/XMLSchema");
... = new XElement(ns + "element");

See the example here: http://msdn.microsoft.com/en-us/library/bb292758.aspx

Upvotes: 1

archil
archil

Reputation: 39501

If you want to create xml, you should use XmlWriter class

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20620

I wrote a blog about that very subject. You can use a DataTable to save a schema.

Upvotes: 0

Related Questions