C#实现XML转CSV时无法读取OtherFields下键值对如何解决
问题原因分析
- 属性名匹配错误:
<Key>标签上的属性名为name,并非代码中填写的Key name - 取值逻辑错误:
<Value>是<Key>节点的子元素,不属于<Key>的属性,无法通过Attributes集合获取值
修复后实现代码
基于XmlDocument的原生方案
string xmlfile = @"C:/data/WDM/CUSTInvoiceData2019032902.xml"; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(xmlfile); Dictionary<string, string> dictXml = new Dictionary<string, string>(); // 直接通过XPath定位所有Key节点,减少嵌套遍历 XmlNodeList keyNodes = xmldoc.SelectNodes("//OtherFields/Key"); foreach (XmlNode keyNode in keyNodes) { string keyName = keyNode.Attributes["name"].Value; string keyValue = keyNode.SelectSingleNode("Value").InnerText; dictXml.Add(keyName, keyValue); }
更简洁的LINQ to XML方案
using System.Xml.Linq; XDocument xDoc = XDocument.Load(@"C:/data/WDM/CUSTInvoiceData2019032902.xml"); Dictionary<string, string> dictXml = xDoc.Descendants("Key") .ToDictionary( k => k.Attribute("name").Value, k => k.Element("Value").Value );
注意:如果XML中存在多个name属性相同的<Key>节点,直接插入字典会抛出重复键异常,可根据业务需求增加去重逻辑,例如优先取首个匹配值、拼接重复值等。
内容的提问来源于stack exchange,提问作者twbass
相关产品推荐
相关产品推荐

