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">
[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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With