views:

245

answers:

1

Currently, I have an xml file that looks like this...


<ArrayOfService>
    <Service>
     <Name>
      Something
     </Name>
     <Id>
      8003
     </Id>
    </Service>
</ArrayOfService>

This is automatically generated from a class that looks like this...


public class Service{
    public string Name;
    public int Id;

    public Service(){
    }
}

To turn the class into XML, I use...


XmlSerializer xs = new XmlSerializer( typeof(Service) );
xs.Serialize( context.Response.OutputStream, FunctionReturnsTypeService() );

Is there any way to also automatically generate an XSD like this?

EDIT:

Also, is there any way to add this schema to the xml as I'm serializing it?

+2  A: 

The xsd.exe tool (%netsdk20%\bin\xsd.exe) infers a type from an XML document.

(You can also use the /c option to generate classes from an xml doc or schema.)

If you want to embed a reference to a schema into an XML doc, then see here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.xml/2006-12/msg00040.html

Summary:
decorate a member of your type with the XmlAttribute attribute, specifying "schemaLocation" as the name of the attr, and "http://www.w3.org/2001/XMLSchema-instance" as the namespace for that attribute. As this example in C#

[System.Xml.Serialization.XmlAttributeAttribute("schemaLocation",
    Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
private string xsiSchemaLocation = "YourSchema.xsd";
Cheeso
the XSD tool works, but not the /c option (that's for generating classes). I just typed xsd myfile.xml and it generated the schema. Awesome. Now, for the second part of my question.. :D
apandit
right - /c generates classes. Whoops!
Cheeso
For on the fly schema generation,http://stackoverflow.com/questions/336988/xml-serialization-and-schema-without-xsd-exe
apandit