【问题标题】:disabling namespace attributes in serialization在序列化中禁用命名空间属性
【发布时间】:2011-01-24 01:54:44
【问题描述】:

我正在使用以下代码来反序列化一个对象,

        using (MemoryStream memoryStream = new MemoryStream())
        {
            try
            {
                XmlWriterSettings writerSettings1 = new XmlWriterSettings();
                writerSettings1.CloseOutput = false;
                writerSettings1.Encoding = System.Text.Encoding.UTF8;
                writerSettings1.Indent = false;
                writerSettings1.OmitXmlDeclaration = true;
                XmlWriter writer1 = XmlWriter.Create(memoryStream, writerSettings1);

                XmlSerializer xs1 = new XmlSerializer(obj.GetType(), string.Empty);
                xs1.UnknownAttribute += new XmlAttributeEventHandler(xs1_UnknownAttribute);
                xs1.UnknownElement += new XmlElementEventHandler(xs1_UnknownElement);
                xs1.UnknownNode += new XmlNodeEventHandler(xs1_UnknownNode);
                xs1.UnreferencedObject += new UnreferencedObjectEventHandler(xs1_UnreferencedObject);
                xs1.Serialize(writer1, obj);
                writer1.Close();

            }
            catch (InvalidOperationException)
            {
                return null;
            }
            memoryStream.Position = 0;
            serializeObjectDoc.Load(memoryStream);

            return serializeObjectDoc.DocumentElement;

之后,当我检查返回节点时,我得到了两个额外的属性 {Attribute, Name="xmlns:xsi", Value="http://www.w3.org/2001/XMLSchema-instance"} 对象 {System.Xml.XmlAttribute} {Attribute, Name="xmlns:xsd", Value="http://www.w3.org/2001/XMLSchema"} 对象 {System.Xml.XmlAttribute}

我想知道如何禁用这两个属性

【问题讨论】:

  • 为什么要“禁用”这些属性?他们不应该伤害任何东西。
  • 他们应该是一个假设的陈述。我不希望元素中有额外的属性,这就是为什么。我在 xml 中使用相同的节点,由不同的组件读取。我想确保它获得与需要完全相同的输入
  • 我正在回滚编辑后的版本。如果您需要任何编辑,请放置 cmets

标签: c# .net xml serialization


【解决方案1】:

XmlSerializerNamespaces 救援;一个简单(但完整)的例子:

using System.Xml.Serialization;
using System;
public class Foo
{
    public string Bar { get; set; }
    static void Main()
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        XmlSerializer ser = new XmlSerializer(typeof(Foo));
        ser.Serialize(Console.Out, new Foo { Bar = "abc" }, ns);
    }
}

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多