目前您要添加多个元素直接的文件 - 所以你会最终要么没有根元素(如果字典是空的)或潜在的多个根元素(如果字典中有多个条目)。你需要一个根元素,然后是你的字典元素。此外,您正尝试找到一个名为valuesName
的元素,但不添加任何内容,因此如果有任何字典条目,则实际上会得到NullReferenceException
。
幸运的是,它比您做得更容易,因为您可以使用LINQ将字典转换为一系列元素并将其放入文档中。
var doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root",
inputDictionary.Select(kvp => new XElement(valuesName,
new XAttribute("key", kvp.Key),
new XAttribute("value", kvp.Value)))));
doc.Save(@"c:\data.xml");
完整的示例应用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XName valuesName = "entry";
var dictionary = new Dictionary<string, string>
{
{ "A", "B" },
{ "Foo", "Bar" }
};
var doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root",
dictionary.Select(kvp => new XElement(valuesName,
new XAttribute("key", kvp.Key),
new XAttribute("value", kvp.Value)))));
doc.Save("test.xml");
}
}
输出(条目的顺序没有保证的):
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<entry key="A" value="B" />
<entry key="Foo" value="Bar" />
</root>
对此的替代击穿将是:
var elements = inputDictionary.Select(kvp => new XElement(valuesName,
new XAttribute("key", kvp.Key),
new XAttribute("value", kvp.Value)));
var doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("root", elements));
你可能会发现这更简单读。
你能提供关于你的代码的更多细节,比如什么是xDoc和valuesName? – 2014-10-01 15:17:35
确实 - 你有'xData',你忽略了,但不是'xDoc'。目前你的'xData'文档*只是*有一个XML声明......它甚至没有根元素。请提供一个简短的*完整*程序来证明问题。 – 2014-10-01 15:19:55
对不起,感谢您指出这一点。我现在编辑了。当我试图弄清楚我做错了什么时,我尝试了另一个xDocument,但现在这一切都调用xData(只是一个错字)。编辑上述内容。 – Jonny 2014-10-01 15:33:23