views:

29

answers:

2

I have some xml similar to this:

<?xml version="1.0" encoding="utf-8" ?>
<data>
    <resources>
        <resource key="Title">Alpha</resource>
        <resource key="ImageName">Small.png</resource>
        <resource key="Desc">blah</resource>
</resources>
</data>

using linq-xml how can i assign each resource here as a key value pair with the ViewData collection.

Thanks.

+1  A: 
var doc = XDocument.Parse(documentString);
foreach (var res in doc.Root.Descendants("resources")) {
    ViewData[(string) res.Attribute("key")] = res.Value;
}

Should work.

Obalix
Thanks, your answer helped. although I used doc.Descendants, not doc.Root.Descendants
raklos
+1  A: 

assuming you loadt hat xml into an XDocument, you can just iterate on teh descendants. here's a quick example, if it's coming from a string:

var doc = XDocument.Parse(docAsString);
 foreach (var resource in doc.Descendants("resource"))
     ViewData[resource.Attribute("key").Value] = resource.Value;
Paul