从字典创建XML文档问题
我的意图是遍历我可爱的字典(key和value都是字符串)并从中创建一个xml文件。从字典创建XML文档问题
我得到最后一行错误(保存xml)。
“InvalidOperationException未处理 状态文档中的令牌EndDocument将导致无效的XML文档。”
通过这个使用断点寻找它似乎是在到达本月底,只有初始位(外的每个循环)已经做了..
我是半个问什么愚蠢的错误我已经提出,我的一部分是问是否有更加雄辩的方式来做到这一点。
对不起,如果我错过了任何东西,让我知道如果我有,将增加。
XDocument xData = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));
foreach (KeyValuePair<string, string> kvp in inputDictionary)
{
xData.Element(valuesName).Add(
new XElement(valuesName,
new XAttribute("key", kvp.Key),
new XAttribute("value", kvp.Value)));
}
xData.Save("C:\\xData.xml");
目前您要添加多个元素直接的文件 - 所以你会最终要么没有根元素(如果字典是空的)或潜在的多个根元素(如果字典中有多个条目)。你需要一个根元素,然后是你的字典元素。此外,您正尝试找到一个名为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));
你可能会发现这更简单读。
完美的伴侣,非常感谢。我基本上切断了我所做的并遵循了你的方向,而且效果很好。 – Jonny 2014-10-02 08:39:08
尝试以下
XDocument xData = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"));
XElement myXml = new XElement("paramList");// make sure your root and your descendents do not shre same name
foreach (var entry in MyList)
{
myXml.Add(new XElement(valuesName,
new XElement("key", entry.key),
new XElement("value", entry.Value)
));
xData.Add(myXml);
你能提供关于你的代码的更多细节,比如什么是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