为序列化XML生成XSD

时间:2009-06-09 14:52:12

标签: c# xml xml-serialization

目前,我有一个看起来像这样的xml文件......


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

这是从类似这样的类自动生成的......


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

    public Service(){
    }
}

要将类转换为XML,我使用...


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

有没有办法像这样自动生成XSD?

编辑:

另外,有没有办法在我序列化时将这个模式添加到xml中?

1 个答案:

答案 0 :(得分:2)

xsd.exe工具(%netsdk20%\ bin \ xsd.exe)从XML文档中推断出一种类型。

(您还可以使用/ c选项从xml doc或schema中生成类。)

如果要将模式的引用嵌入到XML文档中,请参阅此处: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.xml/2006-12/msg00040.html

要点:
使用XmlAttribute属性装饰您的类型的成员,指定“schemaLocation”作为attr的名称,并将“http://www.w3.org/2001/XMLSchema-instance”指定为该属性的名称空间。正如C#中的这个例子

[System.Xml.Serialization.XmlAttributeAttribute("schemaLocation",
    Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
private string xsiSchemaLocation = "YourSchema.xsd";