XmlWriter中的OmitXmlDeclaration和实现IXmlSerializable

本文关键字:实现 IXmlSerializable OmitXmlDeclaration 中的 XmlWriter | 更新日期: 2023-09-27 18:11:07

我想通过实现IXmlSerializable来创建自定义xml序列化。我有这个实现IXmlSerializable接口的测试类:

[Serializable]
public class Employee : IXmlSerializable
{
    public Employee()
    {
        Name = "Vyacheslav";
        Age = 23;                 
    }
    public string Name{get; set;}
    public int Age { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader reader)
    {
        this.Name = reader["Name"].ToString();
        this.Age = Int32.Parse(reader["Age"].ToString());
    }
    public void WriteXml(XmlWriter writer)
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        XmlWriter newWriter = XmlWriter.Create(writer, settings);
        newWriter.WriteAttributeString("Name", this.Name);
        newWriter.WriteAttributeString("Age", this.Age.ToString());            
    }
}

我想做的是省略xml声明。为此,我创建了XmlWriterSettings的适当实例,并将其作为第二个参数传递,以创建新的XmlWriter。但是当我调试这段代码时,我看到newWriter.Settings.OmitXmlDeclaration被设置为false,并且序列化的数据包含标记。我做错了什么?

实际的序列化是这样的:

        var me = new Employee();
        XmlSerializer serializer = new XmlSerializer(typeof(Employee));
        TextWriter writer = new StreamWriter(@"D:'file.txt");
        serializer.Serialize(writer, me);
        writer.Close();

第二个问题是-如果我想序列化类型的雇员,自定义类型的ContactInfo字段要序列化,我需要实现IXmlSerializable在ContactInfo上吗?

XmlWriter中的OmitXmlDeclaration和实现IXmlSerializable

writer-settings是最外层写入器的函数;您应该将其应用于创建文件的代码,即

using(var file = File.Create("file.txt"))
using(var writer = XmlWriter.Create(file, settings))
{
    serializer.Serialize(writer, me);
}
另外,

不需要来实现IXmlSerializable。您不能在内部级别这样做——太晚了。

例如:

using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Employee 
{
    [XmlAttribute] public string Name { get; set; }
    [XmlAttribute] public int Age { get; set; }
}
class Program
{
    static void Main()
    {
        var settings = new XmlWriterSettings();
        settings.OmitXmlDeclaration = true;
        var me = new Employee {
            Name = "Vyacheslav", Age = 23
        };
        var serializer = new XmlSerializer(typeof (Employee));
        using (var file = File.Create("file.txt"))
        using (var writer = XmlWriter.Create(file, settings))
        {
            serializer.Serialize(writer, me);
        }
    }
}

,如果不需要额外的命名空间,则:

        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        serializer.Serialize(writer, me, ns);

生成文件:

<Employee Name="Vyacheslav" Age="23" />