Answers for "how to convert c# class to xml"

0

convert object to xml c# example code

public class StringUtil
{
  
      public static string Serialize(object dataToSerialize)
        {
            if(dataToSerialize==null) return null;

            using (StringWriter stringwriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(dataToSerialize.GetType());
                serializer.Serialize(stringwriter, dataToSerialize);
                return stringwriter.ToString();
            }
        }

        public static T Deserialize<T>(string xmlText)
        {
            if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

            using (StringReader stringReader = new System.IO.StringReader(xmlText))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
        }
}

//Note 
//StringUtil.Serialize(ObjClass); >> return xml
//StringUtil.Deserialize<ObjClass>(str_xml); >> return object
Posted by: Guest on January-07-2021
0

convert class to xml string

public string ToXML()
    {
        using(var stringwriter = new System.IO.StringWriter())
        { 
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(stringwriter, this);
            return stringwriter.ToString();
        }
    }

 public static YourClass LoadFromXMLString(string xmlText)
    {
        using(var stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(YourClass ));
            return serializer.Deserialize(stringReader) as YourClass ;
        }
    }
Posted by: Guest on July-29-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language