How to get xml object/string from c# object?

beginer
beginer
1544 Points
52 Posts

Suppose I have following c# object:

public class CustomerDemo
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
}
var customerList = new List<CustomerDemo>();

And we want xml as below:

<customers>
<customer>
<CustomerId>1</CustomerId>
<CustomerName>customer 1</CustomerName>
<PhoneNumber>111111111</PhoneNumber>
<Email>customer1@gmail.com</Email>
</customer>
……
……
……
<customer>
<CustomerId>6</CustomerId>
<CustomerName>Customer 6</CustomerName>
<PhoneNumber>1111111111</PhoneNumber>
<Email>customer6@gmail.com</Email>
</customer>
</customers>
Views: 729
Total Answered: 2
Total Marked As Answer: 0
Posted On: 05-Oct-2022 01:01

Share:   fb twitter linkedin
Answers
kikme
kikme
248 Points
12 Posts
         

Use generic method:

public static void SerializeToXml<T>(T anyobject, string xmlFilePath)  
{  
    XmlSerializer xmlSerializer = new XmlSerializer(anyobject.GetType());  
  
    using (StreamWriter writer = new StreamWriter(xmlFilePath))  
    {  
        xmlSerializer.Serialize(writer, anyobject);  
    }  
}

as

SerializeToXml(customerList, xmlFilePath);
Posted On: 18-Oct-2022 02:07
Smith
Smith
2890 Points
78 Posts
         

Try following methods:

public static class XmlSerializer<T> where T : class
    {
        public static string Serialize(T obj)
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
            using (var sww = new StringWriter())
            {
                using (XmlTextWriter writer = new XmlTextWriter(sww) { Formatting = Formatting.None })
                {
                    xsSubmit.Serialize(writer, obj);
                    return sww.ToString();
                }
            }
        }

        public static string SerializeOmitXmlDeclaration<T>(T value)
        {
            var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var serializer = new XmlSerializer(value.GetType());
            var settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            using (var stream = new StringWriter())
            using (var writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, value, emptyNamespaces);
                return stream.ToString();
            }
        }
    }

Use it as 

var xml = XmlSerializer<List<CustomerDemo>>.SerializeOmitXmlDeclaration(customerList);
Posted On: 06-Mar-2023 23:43
 Log In to Chat