How to force a XmlSerializer to serialize elements as attributes of a compiled type?

前端 未结 1 1566
醉梦人生
醉梦人生 2021-01-21 18:23

I\'ve given some predefined XML similar to this:




        
相关标签:
1条回答
  • 2021-01-21 18:52

    You can change the way a class is being serialized/deserialized by altering its serialization attributes at runtime. XmlAttributeOverrides class provides such possibility. The following example code correctly deseralizes the XML you've provided:

    XmlAttributes xa = new XmlAttributes();
    XmlAttributes ya = new XmlAttributes();
    
    xa.XmlAttribute = new XmlAttributeAttribute("X");
    ya.XmlAttribute = new XmlAttributeAttribute("Y");
    
    XmlAttributeOverrides xao = new XmlAttributeOverrides();
    xao.Add(typeof(System.Windows.Point), "X", xa);
    xao.Add(typeof(System.Windows.Point), "Y", ya);
    
    var serializer = new XmlSerializer(typeof(RootClass), xao);
    TextReader textReader = new StreamReader("file.xml");
    
    var result = (RootClass)serializer.Deserialize(textReader);
    
    0 讨论(0)
提交回复
热议问题