Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a reference to an xml schema to XML Serialized Output

When serializing object with the code:

var xmlSerializer = new XmlSerializer(typeof(MyType));
using (var xmlWriter = new StreamWriter(outputFileName))
{
    xmlSerializer.Serialize(xmlWriter, myTypeInstance);
}

In the output xml file I get:

<MyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">

How do I add a reference to xml schema to it, so it looks like this:

<MyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
        xsi:noNamespaceSchemaLocation="mySchema.xsd">
like image 734
Max Avatar asked Jan 05 '11 21:01

Max


1 Answers

[Edit]

You could implement IXmlSerializable explicitly and write/read the xml yourself.

public class MyType : IXmlSerializable
{
    void IXmlSerializable.WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", XmlSchema.InstanceNamespace, "mySchema.xsd");

        // other elements & attributes
    }

    XmlSchema IXmlSerializable.GetSchema()
    {
        throw new NotImplementedException();
    }

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }
}

xmlSerializer.Serialize(xmlWriter, myTypeInstance);

Most likely not an ideal solution but adding the following field and attribute to your class will do the trick.

public class MyType
{
    [XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
    public string Schema = @"mySchema.xsd";
}

Another option is the create your own custom XmlTextWriter class.

xmlSerializer.Serialize(new CustomXmlTextWriter(xmlWriter), myTypeInstance);

Or don't use Serialization

var xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));

var xmlNode = xmlDoc.CreateElement("MyType");
xmlDoc.AppendChild(xmlNode);

xmlNode.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNode.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");

var schema = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
schema.Value = "mySchema.xsd";
xmlNode.SetAttributeNode(schema);

xmlDoc.Save(...);

Hope this helps...

like image 55
Steven K. Avatar answered Sep 22 '22 05:09

Steven K.