【问题标题】:Adding a reference to an xml schema to XML Serialized Output将 xml 模式的引用添加到 XML 序列化输出
【发布时间】:2011-01-05 21:35:30
【问题描述】:

使用代码序列化对象时:

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

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    [编辑]

    您可以显式实现 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(...);
    

    希望这会有所帮助...

    【讨论】:

    • 感谢您提供详细信息。很棒的答案!
    • 请注意,这里可以使用XmlSchema.NamespaceXmlSchema.InstanceNamespace 常量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多