从属性指定的XML读取

时间:2012-07-12 23:45:44

标签: c# xml

我有以下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>

在我的c#代码中,我有一个函数获取一个表示Category“name”属性的字符串,如果该字符串等于该属性,我想获取“Path”标记之间的所有文本。 对于Instance,如果函数获取的字符串参数等于“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

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用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);

您可以将粘贴复制到linqpad或visual studio中,然后运行。