0

我有以下 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# 代码中,我有一个函数,它获取一个表示类别“名称”属性的字符串,如果该字符串等于该属性,我想获取“路径”标签之间的所有文本。例如,如果函数获得一个等于“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

谢谢你。

4

1 回答 1

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 中,它会运行。

于 2012-07-13T00:04:08.633 回答