XmlSerializer property converter

前端 未结 3 765
离开以前
离开以前 2020-12-03 17:57

Suppose we have a class which can be serialized/deserialized by XmlSerializer. It would be like so:

[XmlRoot(\"ObjectSummary\")]
public class Summary
{
              


        
相关标签:
3条回答
  • 2020-12-03 18:20

    Treat the node as a custom type:

    [XmlRoot("ObjectSummary")]
    public class Summary
    {
        public string Name {get;set;}
        public BoolYN IsValid {get;set;}
    }
    

    Then implement IXmlSerializable on the custom type:

    public class BoolYN : IXmlSerializable
    {
        public bool Value { get; set }
    
        #region IXmlSerializable members
    
        public System.Xml.Schema.XmlSchema GetSchema() {
            return null;
        }
    
        public void ReadXml(System.Xml.XmlReader reader) {
            string str = reader.ReadString();
            reader.ReadEndElement();
    
            switch (str) {
                case "Y":
                    this.Value = true;
                    break;
                case "N":
                    this.Value = false;
                    break;
            }
        }
    
        public void WriteXml(System.Xml.XmlWriter writer) {
            string str = this.Value ? "Y" : "N";
    
            writer.WriteString(str);
            writer.WriteEndElement();
        }
    
        #endregion
    }
    

    You can even make that custom class a struct instead, and provide implicit conversions between it and bool to make it even more "transparent".

    0 讨论(0)
  • 2020-12-03 18:21
    using Newtonsoft.Json;
    
    [XmlRoot("ObjectSummary")]
    public class Summary
    {
         public string Name {get;set;}
         public string IsValid {get;set;}
    }
    
    
     //pass objectr of Summary class you want to convert to XML
     var json = JsonConvert.SerializeObject(obj);
     XNode node = JsonConvert.DeserializeXNode(json, "ObjectSummary");
    

    If you have more than one object, put it inside a list and Serialize List.

                    dynamic obj = new ExpandoObject();
                    obj.data = listOfObjects;
                    var json = JsonConvert.SerializeObject(obj);
                    XNode node = JsonConvert.DeserializeXNode(json, "ObjectSummary");
    
    0 讨论(0)
  • 2020-12-03 18:22

    The way I do it - which is suboptimal but have not found a better way - is to define two properties:

    [XmlRoot("ObjectSummary")]
    public class Summary
    {
         public string Name {get;set;}
         [XmlIgnore]
         public bool IsValid {get;set;}
         [XmlElement("IsValid")]
         public string IsValidXml {get{ ...};set{...};}
    
    }
    

    Replace ... with the simple code to read and write the IsValid value to Y and N and read from it.

    0 讨论(0)
提交回复
热议问题