C#中如何提取XML数据并存储至Dictionary?
解决XML提取键值对到Dictionary的问题
1. 先解决List输出显示问题
你看到System.Collections.Generic.List1[CodeListParser]是因为直接输出了List对象本身,没有遍历输出内部元素。需要遍历List中的CodeListParser`实例,访问其属性才能看到实际数据。
2. 修正XML提取逻辑并转存Dictionary
假设你的XML结构为(根据截图推断的典型键值对节点结构):
<Root> <CodeEntry> <Code>001</Code> <Value>示例值1</Value> </CodeEntry> <CodeEntry> <Code>002</Code> <Value>示例值2</Value> </CodeEntry> </Root>
调整CodeListParser类
确保类包含对应属性:
public class CodeListParser { public string Code { get; set; } public string Value { get; set; } }
修正Main方法的提取与转换逻辑
用XmlDocument提取节点后,先存入List,再转换为Dictionary:
static void Main(string[] args) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("你的XML文件路径"); // 若为字符串XML则用LoadXml方法 List<CodeListParser> codeItems = new List<CodeListParser>(); XmlNodeList nodeList = xmlDoc.SelectNodes("//CodeEntry"); // 匹配所有目标节点 foreach (XmlNode node in nodeList) { CodeListParser item = new CodeListParser(); item.Code = node.SelectSingleNode("Code").InnerText; item.Value = node.SelectSingleNode("Value").InnerText; codeItems.Add(item); } // 转换为Dictionary<键, 值> Dictionary<string, string> codeDict = codeItems.ToDictionary(item => item.Code, item => item.Value); // 测试输出Dictionary内容 foreach (var kvp in codeDict) { Console.WriteLine($"键: {kvp.Key}, 值: {kvp.Value}"); } }
3. 常见问题排查
- 确保XPath表达式(如
//CodeEntry)与XML实际节点名称完全匹配 - 检查XML文件路径是否正确,嵌入资源需调整加载方式
- 若XML带命名空间,需添加
XmlNamespaceManager后再使用XPath查询
内容的提问来源于stack exchange,提问作者mariatod
相关产品推荐
相关产品推荐

