0

我想从另一个项目的外部 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");
        // ...
    }
}
4

2 回答 2

2

如果你将你的XmlDocument转换成一个,IEnumerable<XmlNode>你可以获得所有有趣的 LINQ 查询。之后,您可以随心所欲地抓住任何东西。也许是这样的?

var node = xmlDoc.SelectNodes("/configuration/appSettings/add").Cast<XmlNode>()
  .Where(n => n.Attributes["key"].Value == "MyProperty1NameInConfigFile");
于 2013-05-30T15:21:14.883 回答
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");
于 2013-05-30T15:39:37.877 回答