[英]Extracting value from key in xml document using c#
我有一個XML文件,如下所示
<configuration>
<appSettings>
<add key="username1" value="password1"/>
<add key="username2" value="password2"/>
</appsettings>
</configuration>
當我通過密鑰時,我想讀取值字段中的文本。 如何做到這一點是C#。
提前致謝。
如果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;
}
您將必須使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.