Ive been trying to figure out an easy way to go from XML to List. Originally I wrote my program to use properties files like in JAVA to avoid XML but that lead to some restrictions later on.
Below is the XML file I am working with. What I would like to do is go to the <email> section and add every individual value for each <address> within <email> to a list object. I managed to get the list of values but in a single string of text that I would need to parse again, there has to be an easier way to get this to a list. I also tried looking online but I cant find an explanation on how to move from XML to list easily.
using System;
using System.Collections.Generic;
using System.Xml;
namespace Email
{
class Program
{
static void Main(string[] args)
{
//Load in the xml
XmlDocument doc = new XmlDocument();
doc.Load("email.xml");
//Prepare the list
List<string> emails = new List<string>();
//Use XPath to get the nodes of interest
XmlNodeList addresses = doc.DocumentElement.SelectNodes("/config/email/address");
//parse the addresses and put them into the list
foreach (XmlNode address in addresses)
{
emails.Add(address.InnerText);
}
}
}
}
using System.IO;
using System.Xml.Linq;
...
public List<string> GetEmailAddresses()
{
using (StreamReader reader = new StreamReader("config.xml"))
{
return
(
from
e in XDocument.Load(reader).Element("config").Element("email").Elements()
select
e.Value
).ToList();
}
}
Rob
-
Ohhhhh.... Old McDonald was dyslexic, E O I O EEEEEEEEEE.......
I read about LINQ and using that to achieve the process but couldn't quite figure it out. I managed to figure it out by using NextSibling and just knowing the position of the nodes in my XML file which I definitely do not like doing. I will try implementing what you have, looks a lot cleaner and easier to understand.
Bookmarks