获取所有后代LINQ to XML

时间:2014-12-21 16:50:27

标签: c# xml linq

我有这种XML格式,但删除了大部分格式,因为这是我需要提取的唯一信息。我提取的部分命名相似,因此存在名为dict,key,array和string的其他元素 - 即只是从字符串元素中提取值不是一个选项。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>CFBundleIcons</key>
        <dict>
            <key>CFBundlePrimaryIcon</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>AppIcon29x29</string>
                    <string>AppIcon40x40</string>
                    <string>AppIcon60x60</string>
                </array>
            </dict>
        </dict>
        <key>CFBundleIcons~ipad</key>
        <dict>
            <key>CFBundlePrimaryIcon</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>AppIcon29x29</string>
                    <string>AppIcon40x40</string>
                    <string>AppIcon60x60</string>
                    <string>AppIcon76x76</string>
                </array>
            </dict>
        </dict>
    </dict>
</plist>

我最接近的是:

XElement doc = XElement.Load(outputFolder + "\\Info.xml");
IEnumerable<XElement> output = doc.Descendants("key").Where(n => (string)n.Value == "CFBundleIconFiles");
foreach (XElement a in output)
    MessageBox.Show((a.NextNode as XElement).Value);

这会显示两个警报,第一个显示:第一个显示“AppIcon29x29AppIcon40x40AppIcon60x60”,第二个显示“AppIcon29x29AppIcon40x40AppIcon60x60AppIcon76x76”这很烦人,因为到目前为止我已经非常接近了。我也觉得我这样做的方式非常糟糕,会让你的一些人感到畏缩。

提前致谢!

编辑:我想要CFBundleIconFiles数组中的字符串。

1 个答案:

答案 0 :(得分:2)

很简单:

IEnumerable<XElement> output = doc.Descendants("key")
  .Where(n => n.Value == "CFBundleIconFiles");

IEnumerable<string> result = 
  output.SelectMany(a => 
    (a.NextNode as XElement).Descendants().Select(n => n.Value));

MessageBox.Show(string.Join(Environment.NewLine, result));
相关问题