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

如何使用XmlDocument方法打印RESX文件特定节点内的文本?

在C#中读取自定义XML文件并打印指定节点内容

你的文件是自定义XML结构(非标准RESX格式),可以用C#的XML处理类读取resheader和data节点下的value文本,以下是两种常用实现方式:

方法一:使用XmlDocument(传统DOM方式)

适合传统.NET框架项目,通过XPath定位目标节点:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // 替换为你的XML文件实际路径
        string xmlFilePath = @"C:\YourPath\users.xml";

        XmlDocument doc = new XmlDocument();
        doc.Load(xmlFilePath);

        // 读取所有resheader节点下的value文本
        Console.WriteLine("=== resheader 下的value内容 ===");
        XmlNodeList resheaderValues = doc.SelectNodes("//resheader/value");
        foreach (XmlNode node in resheaderValues)
        {
            Console.WriteLine(node.InnerText.Trim());
        }

        // 读取所有data节点下的value文本
        Console.WriteLine("\n=== data 下的value内容 ===");
        XmlNodeList dataValues = doc.SelectNodes("//data/value");
        foreach (XmlNode node in dataValues)
        {
            Console.WriteLine(node.InnerText.Trim());
        }
    }
}

方法二:使用XDocument(LINQ to XML)

代码更简洁,适合.NET Core/.NET 5+项目:

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

class Program
{
    static void Main()
    {
        string xmlFilePath = @"C:\YourPath\users.xml";

        XDocument doc = XDocument.Load(xmlFilePath);

        // 遍历resheader下的value节点
        Console.WriteLine("=== resheader 下的value内容 ===");
        foreach (var valueElem in doc.Descendants("resheader").Elements("value"))
        {
            Console.WriteLine(valueElem.Value.Trim());
        }

        // 遍历data下的value节点
        Console.WriteLine("\n=== data 下的value内容 ===");
        foreach (var valueElem in doc.Descendants("data").Elements("value"))
        {
            Console.WriteLine(valueElem.Value.Trim());
        }
    }
}

注意事项

  • 替换代码中的xmlFilePath为你的XML文件实际路径
  • 若文件路径包含特殊字符,使用@符号避免转义问题
  • 若XML文件编码不是UTF-8,加载时可指定对应编码参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:20:25