Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Write List to XML and back
Message
De
10/12/2015 13:54:29
 
 
À
10/12/2015 12:56:14
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Versions des environnements
Environment:
C# 4.0
OS:
Windows 10
Network:
Windows 2008 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01628791
Message ID:
01628811
Vues:
36
>>>Hi,
>>>
>>>I have been Googling for this question and find many suggestions but none that I understand and see simple.
>>>
>>>I have a List (example below) and I want it to create an XML file and save it in a folder.
>>>
>>>
>>>List<string> MyList = new List<string>();
>>>MyList.Add( "ABC" );
>>>MyList.Add( "CBS" );
>>>MyList.Add( "NBC" );
>>>
>>>// Now I want to write the above list to an XML that will look like this:
>>><?xml version="1.0"?>
>>><Choices>
>>>        <Channel>ABC</Channel>
>>>        <Channel>CBS</Channel>
>>>        <Channel>NBC</Channel>
>>></Choices>
>>>
>>>
>>>TIA for any suggestions.
>>
>>Several ways. One using XmlDocument:
List<string> channels = new List<string> {"ABC", "CBS", "NBC"};
>>            XmlDocument xd = new XmlDocument();
>>            var choices = xd.AppendChild(xd.CreateElement("Choices"));
>>            foreach (String s in channels)
>>            {
>>                var channel = xd.CreateElement("Channel");
>>                channel.InnerText = s;
>>                choices.AppendChild(channel);
>>            }
>>            xd.Save(@"d:\test.xml");
Or you could look at XmlSerializer and adding attributes to classes.
>
>Some samples using XmlSerializer can be found at http://stackoverflow.com/questions/2292480/xmlserializer-list-item-element-name.
>
>As for manually creating the Xml, I would suggest using the classes in the System.Xml.Linq namespace. To do this as an extension method:
>
using System.Xml.Linq;
>using System.Linq;
>public static class IEnumerableExtensions
>    {
>        public static string ToXml< T>(this IEnumerable< T> source, string rootTag = "List", string itemTag = "Item")
>        {
>            return new XElement(rootTag, source.Select(item => new XElement(itemTag, item))).ToString();
>        }
>}
>
>
Console.WriteLine(MyList.ToXml("Choices", "Channel"));
Excellent !!
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform