Reputation: 3260
I have the following XML file:
<Categories>
<Category name="TopDown">
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Blu-Ray.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
</Category>
<Category name="SideScroll">
<Path>http://localhost:8080/images/SideScroll/MediaMonkey.png</Path>
<Path>http://localhost:8080/images/SideScroll/Miro.png</Path>
<Path>http://localhost:8080/images/SideScroll/QuickTime.png</Path>
<Path>http://localhost:8080/images/SideScroll/VLC.png</Path>
<Path>http://localhost:8080/images/SideScroll/WinAmp.png</Path>
</Category>
In my c# code, I have a function that gets a string that represents the Category "name" attribute, and if that string equals to that attribute I'd like to get all the text between the "Path" tags. For Instance, if the function gets a string parameter that equals "TopDown" the output would be :
http://localhost:8080/images/TopDown/Divx.png
http://localhost:8080/images/TopDown/Blu-Ray.png
http://localhost:8080/images/TopDown/Divx.png
http://localhost:8080/images/TopDown/Divx.png
http://localhost:8080/images/TopDown/Divx.png
http://localhost:8080/images/TopDown/Divx.png
Thank you.
Upvotes: 0
Views: 144
Reputation: 12437
You can do this with LINQ To XML:
var xdoc = @"<Categories>
<Category name='TopDown'>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Blu-Ray.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
<Path>http://localhost:8080/images/TopDown/Divx.png</Path>
</Category>
<Category name='SideScroll'>
<Path>http://localhost:8080/images/SideScroll/MediaMonkey.png</Path>
<Path>http://localhost:8080/images/SideScroll/Miro.png</Path>
<Path>http://localhost:8080/images/SideScroll/QuickTime.png</Path>
<Path>http://localhost:8080/images/SideScroll/VLC.png</Path>
<Path>http://localhost:8080/images/SideScroll/WinAmp.png</Path>
</Category>
</Categories>";
var paths = XDocument.Parse(xdoc).Descendants("Category")
.Where(w => (string)w.Attribute("name") == "TopDown")
.Select(s => s.Elements("Path").Select (x => (string)x)).ToList();
foreach (var x in paths)
Console.WriteLine(x);
You can copy paste that into linqpad or visual studio and it'll run.
Upvotes: 1