2014-10-01 88 views
1

我的意圖是遍歷我可愛的字典(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"); 
+2

你能提供關於你的代碼的更多細節,比如什麼是xDoc和valuesName? – 2014-10-01 15:17:35

+0

確實 - 你有'xData',你忽略了,但不是'xDoc'。目前你的'xData'文檔*只是*有一個XML聲明......它甚至沒有根元素。請提供一個簡短的*完整*程序來證明問題。 – 2014-10-01 15:19:55

+0

對不起,感謝您指出這一點。我現在編輯了。當我試圖弄清楚我做錯了什麼時,我嘗試了另一個xDocument,但現在這一切都調用xData(只是一個錯字)。編輯上述內容。 – Jonny 2014-10-01 15:33:23

回答

4

目前您要添加多個元素直接的文件 - 所以你會最終要麼沒有根元素(如果字典是空的)或潛在的多個根元素(如果字典中有多個條目)。你需要一個根元素,然後是你的字典元素。此外,您正嘗試找到一個名爲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)); 

你可能會發現這更簡單讀。

+0

完美的伴侶,非常感謝。我基本上切斷了我所做的並遵循了你的方向,而且效果很好。 – Jonny 2014-10-02 08:39:08

1

嘗試以下

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);