0

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?

apandit
  • 3,304
  • 1
  • 26
  • 32
  • what do you mean "add this schema to the XML"? What do you want the output to look like, to contain? – Cheeso Jun 09 '09 at 15:08
  • I want the generated xml to have something like this at the top: – apandit Jun 09 '09 at 15:10
  • xmlns="foo" indicates a namespace, not a schema. If you want a specific xml namespace to be used when serializing a type, then you can use [XmlType(Namespace="Foo")] as an attribute on the type. – Cheeso Jun 09 '09 at 15:15
  • I think what you may want is xsi:schemaLocation, in which case, see here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.xml/2006-12/msg00040.html – Cheeso Jun 09 '09 at 15:19
  • Add that link to your answer, I'll accept it. Looks like what i needed. – apandit Jun 09 '09 at 15:25

1 Answers1

2

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
  • 189,189
  • 101
  • 473
  • 713
  • 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 Jun 09 '09 at 15:06
  • For on the fly schema generation, http://stackoverflow.com/questions/336988/xml-serialization-and-schema-without-xsd-exe – apandit Jun 09 '09 at 15:26
  • The field xsiSchemaLocation needs to be public. – row1 Jul 29 '11 at 03:00