[英]Reading from XML specified by attribute
I have the following XML file: 我有以下XML文件:
<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. 在我的C#代码中,我有一个函数,该函数获取代表“名称”类别属性的字符串,如果该字符串等于该属性,我想获取“路径”标签之间的所有文本。 For Instance, if the function gets a string parameter that equals "TopDown" the output would be :
对于实例,如果函数获取的字符串参数等于“ TopDown”,则输出为:
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. 谢谢。
You can do this with LINQ To XML: 您可以使用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. 您可以将其复制粘贴到linqpad或Visual Studio中,然后它将运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.