At work, if you need to deal with XML, you will inevitably encounter situations where you need to convert a type collection into XML format. The previous method was rather clumsy and needed to write a converted function for different types. But after contacting reflection, we know that reflection can be used to read all members of a type, which means that we can create more general methods for different types. This example does this: using reflection, read all attributes of a type, and then convert the attributes into attributes or child elements of an XML element. The following comments are quite complete, so I won’t say much, so I need to read the code if I need to!
using System; using ; using ; using ; using ; using ; namespace GenericCollectionToXml { class Program { static void Main(string[] args) { var persons = new[]{ new Person(){Name="Li Yuanfang",Age=23}, new Person(){Name="Die Renjie",Age=32} }; (CollectionToXml(persons)); } /// <summary> /// Convert collections into data tables /// </summary> /// <typeparam name="T">Generic Parameters (type of collection member)</typeparam> /// <param name="TCollection">Generic Collection</param> /// <returns> XML format string for collection</returns> public static string CollectionToXml<T>(IEnumerable<T> TCollection) { //Define an array of elements var elements = new List<XElement>(); //Add elements from the collection to the element array foreach (var item in TCollection) { //Get the specific type of generic Type type = typeof(T); //Define the attribute array, XObject is the base class of XAttribute and XElement var attributes = new List<XObject>(); //Get all attributes of the type and add attributes and values to the attribute array foreach (var property in ()) //Get the attribute name and attribute value and add it to the attribute array (can also be added as child elements to the attribute array, just change XAttribute to XElement) (new XAttribute(, (item, null))); //Add attribute array to element (new XElement(, attributes)); } //Initialize the root element, and use the element array as a child element of the root element, returning the string format of the root element (XML) return new XElement("Root", elements).ToString(); } /// <summary> /// Human (test data class) /// </summary> class Person { /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// age /// </summary> public int Age { get; set; } } } }
Output the attribute as attribute:
<Root> <Person Name="Li Yuanfang" Age="23" /> <Person Name="Die Renjie" Age="32" /> </Root>
Output the attribute as a child element:
<Root> <Person> <Name>Li Yuanfang</Name> <Age>23</Age> </Person> <Person> <Name>Di Renjie</Name> <Age>32</Age> </Person> </Root>
The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!