You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从app.config XML文件的低层级节点读取值列表?

读取app.config中低层级节点内容的方法

我平时处理这类读取app.config深层节点的需求时,常用两种实用的方法,下面结合你给的示例config文件来具体说明:

方法一:使用XmlDocument(适配传统.NET Framework项目)

这种方法比较直观,适合习惯DOM操作的场景:

using System.Xml;
using System;

// 加载app.config文件
XmlDocument doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// 定位到目标节点路径:configuration -> references -> firstLevel -> ref
XmlNodeList refNodes = doc.SelectNodes("/configuration/references/firstLevel/ref");

// 遍历节点获取name属性值
foreach (XmlNode node in refNodes)
{
    string nameValue = node.Attributes["name"]?.Value;
    if (!string.IsNullOrEmpty(nameValue))
    {
        Console.WriteLine(nameValue); // 输出 first1、first2、first3
    }
}

方法二:使用LINQ to XML(更简洁,推荐)

如果项目支持,LINQ to XML的写法会更简洁优雅:

using System.Xml.Linq;
using System;
using System.Linq;

// 加载配置文件
XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

// 精准定位层级并提取name属性
var refNames = xDoc.Root?
                   .Element("references")?
                   .Element("firstLevel")?
                   .Elements("ref")
                   .Select(n => n.Attribute("name")?.Value)
                   .Where(v => !string.IsNullOrEmpty(v));

// 遍历输出结果
if (refNames != null)
{
    foreach (string name in refNames)
    {
        Console.WriteLine(name);
    }
}

如果需要匹配更多层级的节点,也可以用Descendants方法批量筛选,不过要注意加上层级判断避免误匹配其他同名节点。

内容的提问来源于stack exchange,提问作者thatOneGuy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:39:52