获取所有后代 LINQ to XML

本文关键字:to XML LINQ 后代 获取 | 更新日期: 2023-09-27 18:34:48

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

<?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数组中的字符串。

获取所有后代 LINQ to XML

很简单:

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));