[英]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.