[英]Parsing XML using C#, getting attribute value
我有以下(簡體)記事本文件,據我了解,該文件是XML文本:
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="Active_01" value="1">
</add>
</appSettings>
我正在嘗試使用C#解析它。
到目前為止,我有以下內容:
public class RFIDScanner
{
public void GetScannerConfigFile()
{
string File = ConfigurationManager.AppSettings["RFIDScannerConfiguration"];
XmlDocument doc = new XmlDocument();
doc.Load(File);
XmlNode node = doc.DocumentElement.SelectSingleNode("/appSettings");
String nodename = node.Name;
}
}
到目前為止,我知道這都是正確的,因為:
nodename = appSettings
應該是這樣。
我的問題是,如何從字段“ Active_01”中檢索值“ 1”。
我現在知道節點“ add”是節點“ appSettings”的子節點,並且正在嘗試找出如何獲取存儲在其中的值。
有很多方法,一種是使用上面使用的功能來使用XPath:
var value = doc.DocumentElement.SelectSingleNode("/appSettings/add/@value");
另一個選擇是使用xml序列化 :
您將定義類如下:
public class add
{
[XmlAttribute]
public string key;
[XmlAttribute]
public int value;
}
public class appSettings
{
public add add;
}
然后反序列化如下:
var ser = new XmlSerializer(typeof(appSettings));
var xmlReader = new XmlTextReader(new StringReader(s));
appSettings settings = (appSettings) ser.Deserialize(xmlReader);
xmlReader.Close();
然后,您可以從settings
獲取值
不知道您是否要從鍵Active_01
解析“ 1”,還是從值中獲取1
。 無論如何,您都可以使用以下代碼:
public void GetScannerConfigFile()
{
string File = ConfigurationManager.AppSettings["RFIDScannerConfiguration"];
XmlDocument doc = new XmlDocument();
doc.Load(File);
var yourFile = doc.DocumentElement;
if (yourFile == null) return;
// Here you'll get the attribute key: key = Active_01 - which can be simply parsed for getting only the "1"
string key = yourFile.ChildNodes[0].Attributes["key"].Value;
// Here you'll get the number "1" from the value attribute.
string value = yourFile.ChildNodes[0].Attributes["value"].Value;
}
我在我的代碼中使用了這種方法,將值添加到xml可能會有所幫助
var surveyTypeList = new XElement("SurveyTypes");
foreach (var item in modelData.SurveyTypeList)
{
if (item.IsSelected)
{
var surveyType = new XElement("SurveyType");
var id = new XElement("Id");
id.Add(item.Value);
// **var i= id.Value**
surveyType.Add(id);
surveyTypeList.Add(surveyType);
}
}
您可以通過代碼中的var i = id.Value獲得價值;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.