-
XML to List
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.
Code:
<config>
<settings>
<configName></configName>
<fileLocation></fileLocation>
<exit></exit>
</settings>
<sendMail>
<address></address>
</sendMail>
<email>
<address></address>
<address></address>
<address></address>
<address></address>
</email>
<ccemail>
<address></address>
<address></address>
<address></address>
<address></address>
</ccemail>
<keywords>
<value></value>
<value></value>
<value></value>
</keywords>
</config>
-
Re: XML to List
Ok I got a little bit farther with the following code
Code:
List<string> emails = new List<string>();
XDocument derps = XDocument.Load("config.xml");
foreach (var derp in derps.Descendants("email"))
{
}
Basically if I point at the beginning of the foreach loop the derp contains the following:
Code:
<email>
<address>moo@moo.com</address>
<address>moo@moo.com</address>
<address>moo@moo.com</address>
<address>moo@moo.com</address>
</email>
Unfortunately I cant for the life of me find a way to take that and push it into a list.
-
Re: XML to List
Try this:
Code:
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);
}
}
}
}
-
Re: XML to List
OR... using LINQ:
Code:
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();
}
}
-
Re: XML to List
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.
Code:
XmlNode node = xmlDoc.DocumentElement.FirstChild.NextSibling;
foreach (XmlNode child in node.ChildNodes)
{
eD.Add(child.InnerText);
}