开发者

The xsd.exe generated C# class from the W3C XMLschema.xsd (the schema for xsd validation) is not accepted by the C# XmlSerializer

开发者 https://www.devze.com 2023-03-13 09:14 出处:网络
The utility \'xsd.exe\' will generate c# class source code that corresponds in various ways to the information in an xsd schema file.

The utility 'xsd.exe' will generate c# class source code that corresponds in various ways to the information in an xsd schema file.

So, I download the schema file 'XMLSchema.xsd' located at "http://www.w3.org/2001/XMLSchema" -- this is the schema for the xsd files themselves.

I generate the C# class corresponding to the 'schema for schemas', using:

xsd.exe /classes /namespace:w3c XMLSchema.xsd

So far so good. I get a file 'XMLSchema.cs' containing a C# class 'schema', and other stuff, in namespace 'w3c' which I proceed to add to a C# project which also contains the following:

try
{
    XmlSerializer loader = new XmlSerializer(typeof(w3c.schema));

    //never here!! previous line throws!

    FileStream fs = new FileStream(
        @"M:\src\Interfaces\MyClass1.xsd", FileMode.Open, FileAccess.Read
        );

    object fromXml = loader.Deserialize(fs);
    w3c.schema MyClass1Schema = 开发者_如何学编程(w3c.schema)fromXml;
}
catch(Exception e)
{
}

Unfortunately, it throws the following error on the first line of the try block:

The XML element 'annotation' from namespace 'http://www.w3.org/2001/XMLSchema' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

Has anyone experienced this error?

I would rather not make any modification to the generated file 'XMLSchema.cs'.

I have also (originally) tried:

xsd /classes XMLSchema.xsd

(and no namespacing in the C# test code) with the same result.


I'm going to guess that the problem has nothing to do with .NET namespaces, as you guessed with your second command, but with XML namespaces.

The problem it appears you're having is that the XSD file defines a namespace (likely, xsd) that the XML Serializer already uses (for, surprise surprise, the XSD for the XSD).

I am not sure what the XML spec says for two equivalent namespaces with different identifiers, but the proper way to resolve this would be to change the namespace of your input XSD file. Of course, this will render it invalid, but it would stop XmlSerializer from throwing, I think.


I believe you cannot use namespace in typeof(), instead put the name of the object (instance of class) that you are trying to serialize.

0

精彩评论

暂无评论...
验证码 换一张
取 消