Reading an XML file into a collection

M

Mark Collard

Hello

I've created the following XML file:
<?xml version="1.0" encoding="utf-8"?>
<Company>
<Languages>
<Language>
<Name>English</Name>
<Code>1234</Code>
<Connect>54</Flag>
</Language>
<Language>
<Name>French</Name>
<Code>4567</Code>
</Language>
</Languages>
</Company>

I've also created a Language class that has the following properties
- string Name
- int Code
- int Connect

And a Language collection class called LanguageCollection.

Can someone please tell me what is the easiest / best way is to read the
values from the XML file and store them in a collection of Language of
objects.

Please note that not ever Language will be fully populated in the XML file.
For example, the French language doesn't have a Connect value in the above
XML file


Thank you for your help.
 
J

Jon Skeet [C# MVP]

Can someone please tell me what is the easiest / best way is to read the
values from the XML file and store them in a collection of Language of
objects.

Which version of .NET are you using? With .NET 3.5 you can use LINQ to
XML, which will make life *much* easier.
 
K

Kevin Spencer

Create XML-Serializable classes. Use the XML format which they produce when
serialized. Then you can just deserialize the XML back to class instances.

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 
S

sloan

I did a write up for this here:
http://sholliday.spaces.live.com/Blog/cns!A68482B9628A842A!114.entry


But as Jon mentions, if you have 3.5, then look at linq, there are many more
features with it.


You can use the top link to see if you can massage the xml format to what
you need.

If you have no control over the xml, then you have 2 options:

1. Write code to parse the xml (XmlReader or XmlDocument).

2. Check this out.
http://sholliday.spaces.live.com/Blog/cns!A68482B9628A842A!148.entry
The idea being....change your below xml to an xml that works with the
XmlSerializer.

Good luck.


Try to post what you end up doing.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

As Jon said depending of what version you have it's easier or not.
Below you can find the code in LINQ.
BTW , you had an error in your XML : <Connect>54</Flag> is incorrect.



XDocument xd = XDocument.Load(@"C:\xmluploads\New Text
Document.txt");
var d = from c in xd.Descendants("Language")
select new C
{
Name = (string)c.Element("Name") ?? "Unknow",
Code = (int?)c.Element("Code") ?? -1,
Connect = (int?)c.Element("Connect") ?? -1
};
foreach (var i in d)
Console.WriteLine(i.Connect);

class C
{
public string Name;
public int Code;
public int Connect;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top