使用Linq而不是foreach

时间:2013-05-30 15:10:54

标签: c# xml

我想从另一个项目的外部app.config(appSettings)加载一些配置,加载的值必须保存在我的一些属性中。这里(见代码中的注释)是我想要做的:

XmlDocument xmlDoc = MyXmlDocument;
if (xmlDoc != null)
{
    XmlNodeList appSettings = xmlDoc.SelectNodes("/configuration/appSettings/add");
    if (appSettings != null && appSettings.Count > 0)
    {
        foreach (XmlNode node in appSettings)
        {
            XmlAttribute keyAttr = node.Attributes["key"];
            if (keyAttr != null)
            {
                if (keyAttr.Value == "MyProperty1NameInConfigFile") MyProperty1 = node.Attributes["value"].Value; 
                // ....
            }
        }


        // Instead of using foreach loop, I want to use Linq like this:
        var node = get me the node that has the keyAttribute.Value == "MyProperty1NameInConfigFile"
        MyProperty1 = node.Attributes["value"].Value; 

        // If I got this, then I can later use another method for each property like this:
        SaveConfigToMyProperty(ref MyProperty1, "MyProperty1NameInConfigFile");
        SaveConfigToMyProperty(ref MyProperty2, "MyProperty2NameInConfigFile");
        // ...
    }
}

2 个答案:

答案 0 :(得分:2)

如果您将XmlDocument投射到IEnumerable<XmlNode>,您可以获得所有有趣的LINQ查询。之后,你可以抓住任何你喜欢的东西。也许是这样的?

var node = xmlDoc.SelectNodes("/configuration/appSettings/add").Cast<XmlNode>()
  .Where(n => n.Attributes["key"].Value == "MyProperty1NameInConfigFile");

答案 1 :(得分:0)

这是一个XElement解决方案,更适合与Linq合作;

string xml = "";//xml as string;
var txtReader = new XmlTextReader(xml, XmlNodeType.Element);
var root = XElement.Load( txtReader );

var node = root.XPathSelectElements("/configuration/appSettings/add")
                .FirstOrDefault(n => 
                    n.Attributes["key"] != null && 
                    n.Attributes["key"].Value == "MyProperty1NameInConfigFile");