将对xml架构的引用添加到XML序列化输出

时间:2011-01-05 21:35:30

标签: c# xml-serialization

使用代码序列化对象时:

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

在输出xml文件中,我得到:

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

如何向其添加对xml架构的引用,如下所示:

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

1 个答案:

答案 0 :(得分:16)

[编辑]

您可以显式实现IXmlSerializable并自己编写/读取xml。

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);

很可能不是理想的解决方案,但在您的课程中添加以下字段和属性就可以了。

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

另一个选择是创建自己的自定义XmlTextWriter类。

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

或者不要使用序列化

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(...);

希望这会有所帮助......