Can I serialize Anonymous Types as xml?

后端 未结 7 2062
误落风尘
误落风尘 2020-11-27 04:48

I understood that anonymous types are marked private by the compiler and the properties are read-only. Is there a way to serialize them to xml (without deserialize) ? It wor

7条回答
  •  一个人的身影
    2020-11-27 05:21

    I know this is an old post, but my solution converts an anonymous type to XML in only 2 lines of code.

    First convert you anonymous type to JSON, and then from JSON to XML.

    var jsonText = JsonConvert.SerializeObject(data);           // convert to JSON
    XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonText); // convert JSON to XML Document
    

    Sample

    var data = new       // data - Anonymous Type
    {
        Request = new
        {
            OrderNumber = 123,
            Note = "Hello World"
        }
    };
    
    var jsonText = JsonConvert.SerializeObject(data);           
    XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonText);
    
    Console.WriteLine(doc.OuterXml);                            
    

    Output

    
        123
        Hello World
    
    

提交回复
热议问题