简体   繁体   中英

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">

[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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM