代码之家  ›  专栏  ›  技术社区  ›  Ravisha

在序列化中禁用命名空间属性

  •  1
  • Ravisha  · 技术社区  · 15 年前

    正在使用以下代码反序列化对象,

            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”object system.xml.xmltattribute_ attribute,name=“xmlns:xsd”,value=“http://www.w3.org/2001/xmlschema”object system.xml.xmltattribute

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

    1 回复  |  直到 6 年前
        1
  •  3
  •   Marc Gravell    15 年前

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