我正在尝试导入xml数据并导出到csv文件。我收到XElement键为null的错误:
string FILEMNAME = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"configuration\" + SelectedConfig.Text + ".xml");
{
XDocument doc = XDocument.Load(FILEMNAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
Dictionary<string, string> dict = root.Descendants(ns + "Table1")
.GroupBy(x => (string)x.Element(ns + "Column3"), y => (string)y.Element(ns + "Column2"))
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
using (StreamWriter file = new StreamWriter("myfile.ini"))
foreach (var entry in dict)
file.WriteLine("set {0} = {1}", entry.Key, entry.Value);
}
答案 0 :(得分:0)
当您在string
上显式转换为x.Element
时,如果未找到该元素,它将返回null
(而不是空引用异常)。
解决此问题的一种方法是使用空合并运算符(??
)分配一个非空值:
(string)x.Element(ns + "Column3") ?? ""
因此您的LINQ语句如下所示:
Dictionary<string, string> dict = root.Descendants(ns + "Table1")
.GroupBy(x => (string)x.Element(ns + "Column3") ?? "", y => (string)y.Element(ns + "Column2") ?? "")
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
您可能想为空合并运算符分配一个除“”之外的值-这只是一个简单的示例。