How to write a comment to an XML file when using the XmlSerializer?

后端 未结 5 646
刺人心
刺人心 2020-12-01 06:25

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         


        
5条回答
  •  囚心锁ツ
    2020-12-01 07:14

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

    Very simple implementation:

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

    Output:

    
    
      
      1.2
      A
    
    

    Another way, maybe preferable: serialize with default serializer, then perform post-processing, i.e. update XML, e.g. using XDocument or XmlDocument.

提交回复
热议问题