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

beginer
beginer
296 Points
83 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: 104
Total Answered: 1
Total Marked As Answer: 0
Posted On: 05-Oct-2022 01:01

Share:   fb twitter linkedin
Answers
kikme
kikme
40 Points
15 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
 Log In to Chat