使用c#从xml文档中的键中提取值

时间:2017-05-25 09:53:18

标签: c# xml linq

我有一个XML文件如下

 <configuration>
  <appSettings>
   <add key="username1" value="password1"/>
   <add key="username2" value="password2"/>
  </appsettings>
 </configuration>

我希望在传递密钥时读取值字段中的文本。如何做到这一点是c#。

提前致谢。

2 个答案:

答案 0 :(得分:2)

如果linq只是为了好玩,旧的XmlDocument有方法SelectSingleNode,接受xpath

static void Main(string[] args) 
{
    var xmlval =@"<configuration><appSettings><add key='username1' value='password1'/><add key='username2' value='password2'/></appSettings></configuration>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlval);

    for (int i = 1; i < 5; i++) 
    {
        string key = "username" + i.ToString();
        Console.WriteLine("Value for key {0} is {1}", key, getvalue(doc, key));
    }


}

static string getvalue(XmlDocument doc, string key) 
{
    var e = (XmlElement)doc.SelectSingleNode(string.Format( "configuration/appSettings/add[@key='{0}']",key));
    if (e == null)
        return null;
    else
        return e.Attributes["value"].Value; 
}

答案 1 :(得分:0)

您必须使用Linq to XML或XmlDocument等解析XML文件。

例如,使用XmlDocument,您可以执行以下操作:

XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
            xmlDoc.Load("XMLFile1.xml"); // Load the XML document 

            // Get elements           
            XmlNodeList addElements = xmlDoc.GetElementsByTagName("add");
            XmlNode n = addElements.Item(0); //get first {add} Node

            //Get attributes
            XmlAttribute a1 = n.Attributes[0];
            XmlAttribute a2 = n.Attributes[1];

            // Display the results
            Console.WriteLine("Key = " + a1.Name + " Value = " + a1.Value);
            Console.WriteLine("Key = " + a2.Name + " Value = " + a2.Value);