2017-05-25 13 views
0

XML文档中的值我有一个XML文件,如下所示从提取重点用C#

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

我想读值字段中的文本,当我通过的关键。如何做到这一点是C#。

在此先感谢。

+0

的[从app.config文件读取]可能的复制(https://stackoverflow.com/questions/2400097/reading-from-应用程序配置文件) – barakcaf

+1

这通常是一个问题,你会对谷歌而不是StackOverflow。 – Abion47

+1

可能重复[如何解析XML文件?](https://stackoverflow.com/questions/55828/how-does-one-parse-xml-files) – Abion47

回答

1

如果LINQ只是为了好玩,老XmlDocument的有方法的SelectSingleNode,接受的XPath

static void Main(string[] args) 
{ 
    var xmlval [email protected]"<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; 
} 
0

你将不得不解析XML文件,使用LINQ to XML或类似的XmlDocument的东西。

例如使用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);