Can I Serialize XML straight to a string instead of a Stream with C#?

后端 未结 4 816
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 10:39

This example uses a StringWriter to hold the serialized data, then calling ToString() gives the actual string value:

P         


        
4条回答
  •  囚心锁ツ
    2020-12-08 11:20

    I created this helper method, but I haven't tested it yet. Updated the code per orsogufo's comments (twice):

    private string ConvertObjectToXml(object objectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
        StringWriter stringWriter = new StringWriter();
    
        xmlSerializer.Serialize(stringWriter, objectToSerialize);
    
        return stringWriter.ToString();
    }
    

提交回复
热议问题