使用 C# 解析 XML,获取属性值

本文关键字:获取 属性 XML 解析 使用 | 更新日期: 2023-09-27 18:34:24

我有以下(简化的)记事本文件,据我所知是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"的子节点,并且试图弄清楚如何获取存储在其中的值。

使用 C# 解析 XML,获取属性值

不确定是要从键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;
    }

有很多方法,一种是使用你上面使用的函数来使用 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中获取值

我在代码中使用了这种方式向 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 在你的代码中获取值;