如何使用XmlSerializer时,以撰写评论,以XML文件?如何使用、文件、XmlSerializer、XML

2023-09-02 01:59:16 作者:ゞ从骨子里透出来的轻浮╮

我有我序列化到XML流的对象美孚。

I have an object Foo which I serialize to an XML stream.

public class Foo {
  // The application version, NOT the file version!
  public string Version {get;set;}
  public string Name {get;set;}
}

Foo foo = new Foo { Version = "1.0", Name = "Bar" };
XmlSerializer xmlSerializer = new XmlSerializer(foo.GetType());

这工作快速,简便,当前确实需要的一切。

This works fast, easy and does everything currently required.

我遇到的问题是,我需要保持一些小的话一个单独的文档文件。正如上面的例子中,名称是显而易见的,但版本是应用程序版本,而不是数据文件的版本为一体可以预料在这种情况下。我有更多类似的小事情我想澄清一个注释。

The problem I'm having is that I need to maintain a separate documentation file with some minor remarks. As in the above example, Name is obvious, but Version is the application version and not the data file version as one could expect in this case. And I have many more similar little things I want to clarify with a comment.

我知道我能做到这一点,如果我使用 WriteComment()的功能手动创建我的XML文件,但有一个可能的属性或替代语法,我可以实现这样我可以继续使用该序列化功能?

I know I can do this if I manually create my XML file using the WriteComment() function, but is there a possible attribute or alternative syntax I can implement so that I can keep using the serializer functionality?

推荐答案

是不是可以使用默认的基础设施。你需要实现的IXmlSerializable 你的目的。

Isn't possible using default infrastructure. You need to implement IXmlSerializable for your purposes.

非常简单的实现:

public class Foo : IXmlSerializable
{
    [XmlComment(Value = "The application version, NOT the file version!")]
    public string Version { get; set; }
    public string Name { get; set; }


    public void WriteXml(XmlWriter writer)
    {
        var properties = GetType().GetProperties();

        foreach (var propertyInfo in properties)
        {
            if (propertyInfo.IsDefined(typeof(XmlCommentAttribute), false))
            {
                writer.WriteComment(
                    propertyInfo.GetCustomAttributes(typeof(XmlCommentAttribute), false)
                        .Cast<XmlCommentAttribute>().Single().Value);
            }

            writer.WriteElementString(propertyInfo.Name, propertyInfo.GetValue(this, null).ToString());
        }
    }
    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class XmlCommentAttribute : Attribute
{
    public string Value { get; set; }
}

输出:

<?xml version="1.0" encoding="utf-16"?>
<Foo>
  <!--The application version, NOT the file version!-->
  <Version>1.2</Version>
  <Name>A</Name>
</Foo>

另一种方式,也许preferable:序列化与默认的序列,然后进行后处理,也就是更新XML,如:使用的XDocument 的XmlDocument