如何使用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
相关产品推荐
相关产品推荐

