Blog posts about xml

  • C# classes created from XML with XSD.EXE

    June 07, 2012 | Tags: Tools, XML, C#
    The XSD.EXE tool that is included in Visual Studios command line tools is a bit flawed.

    Running the command first generating an XSD scheme out of your XML file and then creating classes from it:
    xsd MyXml.xml
    xsd MyXml.xsd /classes /n:MyNameSpace.Serialization

    First of all, most likely your array elements will be declared as multi dimensional arrays. If so you'll end up with a "Unable to generate a temporary class" exception and plenty of "error CS0030: Cannot convert type 'Data[]' to 'Data'". (Data is an example return type, yours will probably be named something else, Row is an example element name.)

    The code in the generated class would look something like this:
    [System.Xml.Serialization.XmlArrayItemAttribute("Data", typeof(Data), IsNullable=false)]
    public Data[][] Row ...

    If you actually use multi dimensional arrays, it should really be using typeof(Data[]) instead, like this:
    [System.Xml.Serialization.XmlArrayItemAttribute("Data", typeof(Data[]), IsNullable=false)]
    public Data[][] Row ...

    But if you're just looking for normal one dimensional arrays it's the return type that needs to be flattened to Data[] instead of Data[][]:
    [System.Xml.Serialization.XmlArrayItemAttribute("Data", typeof(Data), IsNullable=false)]
    public Data[] Row ...

    Read the original solution post here.

    The second problem you may face is if your XML doesn't contains namespaces. It would occur like "<yourrootelement xmlns=""> was not expected.". To fix this, remove the empty Namespace parameters from the XmlRootAttribute in your generated classes. You'll find some alternative fixes for this problem here.