简体   繁体   English

在XML配置文件中获取“密钥”属性

[英]Get “Key” attribute in XML config file

I have an XML file with a structure and trying to get value from "Key" and "Value": 我有一个具有结构的XML文件,并尝试从“键”和“值”中获取值:

  <appSettings>
  <add key="Url" value=" http://book.jetstar.com/"/>

  <!--Id's or Xpath-->
  <add key="Origin" value="somevalue"/>
  <add key="Destination" value="somevalue"/>
  <add key="Adult" value ="somevalue" />
  <add key="somevalue"/>

  <!--Controls-->
  <add key="OriginCtrl" value=" Input"/>
  <!--Textbox-->
  <add key="DestinationCtrl" value=" Input"/>
  <add key="AdultCtrl" value=" Select"/>
  <add key="SearchFlightsCtrl " value=" Button"/>

</appSettings> 

I am trying to create a loop that loops through the XML and get value of these "key" and "value". 我试图创建一个循环遍历XML并获取这些“键”和“值”的值的循环。 The code I am writing is 我正在写的代码是

            XmlDocument xmlDoc = new XmlDocument();
            XmlNodeList xmlnodelist;        
            string keyname = "";
            string keyvalue = "";
            xmlDoc.Load(filename);
            xmlnodelist = xmlDoc.SelectNodes("appSettings");

            foreach (XmlNode nodes in xmlnodelist)
            {
                keyname = nodes.Attributes.GetNamedItem("key").Value;
                keyvalue = nodes.Attributes.GetNamedItem("value").Value;
            }

The error with "object not set to an instance" rises when i try to run this piece of code. 当我尝试运行这段代码时,出现“对象未设置为实例”的错误。 I wonder if there is errors in the code where getting the Value. 我想知道代码中是否有错误获取值。 Any advices would be appreciated. 任何建议,将不胜感激。

由于您要获取appSettings ,因此应使用

xmlDoc.SelectNodes("appSettings/add");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM