0

Here is the XML I have in a file:

SPECIAL NOTE: This is a question for Windows Phone 7, not general C#

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <item>
        <date>01/01</date>
        <word>aberrant</word>
        <def>straying from the right or normal way</def>
    </item>

    <item>
        <date>01/02</date>
        <word>Zeitgeist</word>
        <def>the spirit of the time.</def>
    </item>
</rss>

I need it in a List (aka array) of Dictionary objects. Each Dictionary represents an <item>. Each element like <word> is the key with type string and each value like "Zeitgeist" is the value with type string.

Is there any easy way to do this? I'm coming from Objective-C and iOS so this is completely new to me with .NET and C#.

Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

3 Answers3

2

LINQ-to-XML makes it pretty easy. Here's a complete example:

        public static void Main(string[] args)
        {
            string xml = @"
<rss version='2.0'>
    <item>
        <date>01/01</date>
        <word>aberrant</word>
        <def>straying from the right or normal way</def>
    </item>

    <item>
        <date>01/02</date>
        <word>Zeitgeist</word>
        <def>the spirit of the time.</def>
    </item>
</rss>";
            var xdoc = XDocument.Parse(xml);
            var result = xdoc.Root.Elements("item")
                .Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))
                .ToList();

        }

Instead of loading from a string with XDocument.Parse(), you would probably do XDocument.Load(filename) but either way you get an XDocument object to work with (I did a string just for example).

JohnD
  • 14,327
  • 4
  • 40
  • 53
1

You can use Linq-Xml to do this:

var doc = XDocument.Parse(xml); //xml is a String with your XML in it.
doc
.Root                         //Elements under the root element.
.Elements("item")             //Select the elements called "item".
.Select(                      //Projecting each item element to something new.
    item =>                   //Selecting each element in the item.
        item                  //And creating a new dictionary using the element name
        .Elements()           // as the key and element value as the value. 
        .ToDictionary(xe => xe.Name.LocalName, xe => xe.Value))
.ToList();
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
0

Yes, there is an easy way, it's called LINQ to XML.

Some resources:

Parsing complex XML with C#

LINQ to read XML

http://msdn.microsoft.com/en-us/library/bb387098.aspx

Hope this helps...

Community
  • 1
  • 1
surfen
  • 4,644
  • 3
  • 34
  • 46