views:

960

answers:

2

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"&gt;
</gpx>
+7  A: 

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.

dtb
Perfect thanks!
David Hayes
What would it set the schemaLocation to? The location from which XSD.EXE used it is not likely to be available on the web, which is where the user of `xsi:schemaLocation` would need to find it.
John Saunders
@John: Maybe there is some option to specify the value in the xsd file?
dtb
There is no such option.
John Saunders
+1  A: 

You'll have to do this on your own. There's no way for XML Serialization to know where you want your schema to go in any case.

Try this, though I haven't tested it yet:

[XmlRoot(ElementName = "gpx", Namespace = GPX_NAMESPACE)]
public class WhateverAGpxIs
{
    private const string GPX_NAMESPACE = "http://www.topografix.com/GPX/1/1";

    private const string XSI_NAMESPACE =
        "http://www.w3.org/2001/XMLSchema-instance";

    [XmlAttribute(AttributeName = "creator")]
    public string Creator = "ExpertGPS 1.1 - http://www.topografix.com";

    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces =
        new XmlSerializerNamespaces(
            new[]
                {
                    new XmlQualifiedName("xsi", XSI_NAMESPACE),
                    new XmlQualifiedName(string.Empty, GPX_NAMESPACE)
                });

    [XmlAttribute(AttributeName = "schemaLocation",
        Namespace = XSI_NAMESPACE)]
    public string SchemaLocation = GPX_NAMESPACE + " " +
                                   "http://www.topografix.com/GPX/1/1/gpx.xsd";

    [XmlAttribute(AttributeName = "version")]
    public string Version = "1.1";
}
John Saunders