2013-05-30 53 views
0

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

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"); 
     // ... 
    } 
} 
+0

为什么您需要使用XML读取器来使用app.config? –

+1

,因为我正在使用另一个项目的app.config。我想从外部app.config读取设置。 – Stacked

+0

可能希望为这个问题添加一些小技巧,这样人们(比如我)就不会威胁到你。 ;) –

回答

2

如果你投你的XmlDocumentIEnumerable<XmlNode>你可以得到所有的乐趣LINQ查询。之后,你可以抓住你喜欢的任何东西。也许这样?

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

嘎,打我吧> _ < – Sean

+0

谢谢莉莉,加入.FirstOrDefault();在查询结束时将修复编译错误。工作很好。 – Stacked

+0

如果你想使用Linq和XML,那么最好使用XElement而不是XmlDocument – saj

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"); 
+0

好的,但是使用XElement代替使用XmlDocument有什么好处? – Stacked

+0

那么,你不必申请一个不必要的演员来使用Linq库。欲了解更多信息,请参阅: http://blogs.msdn.com/b/codejunkie/archive/2008/10/08/xmldocument-vs-xelement-performance.aspx – saj

相关问题