Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerialization and xsi:SchemaLocation (xsd.exe)

I used xsd.exe to generate a C# class for reading/writing GPX files. How do I get the resultant XML file to include the xsi:schemaLocation attribute eg.

I want the following but xsi:schemaLocation is always missing

<?xml version="1.0"?>
<gpx 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    version="1.1" 
    xmlns="http://www.topografix.com/GPX/1/1"
    creator="ExpertGPS 1.1 - http://www.topografix.com"
    xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
</gpx>
like image 283
David Hayes Avatar asked Sep 10 '09 23:09

David Hayes


2 Answers

Add this to your generated C# class:

[XmlAttribute("schemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string xsiSchemaLocation = "http://www.topografix.com/GPX/1/1 " +
                                  "http://www.topografix.com/GPX/1/1/gpx.xsd";

Apparently the xsd.exe tool does not generate the schemaLocation attribute.

like image 191
dtb Avatar answered Sep 18 '22 14:09

dtb


Instead of modifying the class generated by xsd.exe to add the schemaLocation attribute you can extend the class and add it in your extended class.

Lets say the original schema is called MySchema.xsd and the generated file name is MySchema.cs and the class name is MySchema. Here is what the generated class might look like:

[MySchema.cs]

namespace MyProgram.MySchemas {
    using System.Xml.Serialization;


    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    ...
    public partial class MySchema {

       private string someField;

       ...
       ...
    }
}

(Note that the class is partial. This means we can extend it.)

What you need to do is create another file, in this example we will call it MySchemaExtender.cs. This file will contain another partial class definition with the same class name MySchema:

[MySchemaExtender.cs]

namespace MyProgram.MySchemas {
    using System.Xml.Serialization;

    public partial class MySchema {        
    }
}

Now all you need to do is put the schemaLocation attribute in the extended class. Here is what your final extended class will look like:

[MySchemaExtender.cs]

namespace MyProgram.MySchemas {
    using System.Xml.Serialization;

    public partial class MySchema {
        [XmlAttribute("schemaLocation", Namespace = System.Xml.Schema.XmlSchema.InstanceNamespace)]
        public string xsiSchemaLocation = @"http://someurl/myprogram http://someurl/myprogram/MySchema.xsd";
    }
}

Now if you regenerate the class using xsd.exe you won't have to modify anything.

like image 24
Jan Tacci Avatar answered Sep 20 '22 14:09

Jan Tacci