2012-11-19 44 views
0

我有一個問題,我無法弄清楚是怎麼回事。我想從列表框中將元素插入到我的XML文件中。在列表框中有Menuelem元素,它有一個字符串和一個int變量。將元素添加到列表中的xml

dt = DateTime.Now; 
    XDocument doc = XDocument.Load(path); 

    XElement user = new XElement("user", new XAttribute("id", id), 
         new XElement("order", new XAttribute("id", key), 
          new XElement("date", dt.ToString())) 
        ); 
    doc.Element("orders").Add(user); 
    doc.Save(path); 
    foreach (Menuelem item in listBox6.Items) 
    { 
     int j=0; 
     var menuelem = new XElement("menuelem", new XAttribute("db", j), 
         new XElement("name", item.Nev), 
         new XElement("price", item.Ar)); 
     doc.Element("order").Add(menuelem); //throws nullreferenceexception 
     doc.Save(path); 
     j++; 
    } 

    listBox6.Items.Clear(); 
    label3.Text = ""; 
    key++; 

} 

我想看看我的XML是這樣的:

<?xml version="1.0" encoding="utf-8" ?> 
<orders> 
<user id="0"> 
    <order id="0"> 
    <date>2012.11.19. 2:16:12</date> 
    <menuelem db = "0"> 
    <name>asdasdas</name> 
    <price>1000</price> 
    <menuelem db = "1"> 
    <name>asds</name> 
    <price>2000</price> 
    </order> 
<user id="0"> 
    <order id="1"> 
    <date>2012.11.19. 2:16:15</date> 
    <menuelem db = "0"> 
     <name>asdasdas</name> 
     <price>1000</price> 
    <menuelem db = "1"> 
     <name>asds</name> 
     <price>2000</price> 
    </order> 
</user> 
</orders> 

任何人都可以解決這個使用LINQ?

回答

-1

你的代碼試圖找到「命令」元素作爲僅包含根元素(「訂單」)和作爲結果獲得null文檔的直接子。請參閱Element瞭解有關搜索元素的詳細信息以及何時返回null

您需要正確選擇新插入的元素。簡單的選擇是按名稱使用Descendants,選擇最後一項(這只是添加添加的用戶)

doc.Descendants("order").Last().Add(menuelem); 

更容易的選擇是完全建立「用戶」元素,然後將其添加到樹。比你不需要搜索文檔剛剛添加到它的節點。

+1

-1:如果你想閱讀OP的想法並解決他原來的問題,那麼你顯然是不正確的。 OP希望將「menuitem」元素添加到他剛剛添加的特定用戶,而不是您的解決方案中存在於文檔中的第一個用戶。 –

+0

@DanielT - Fyodor Soikin提供了一個很好的觀點 - 您應該只使用添加的用戶(或者更好地構建用戶而不是添加到文檔中)。 –

+0

感謝所有的答案,我可以讓它工作。 – fzl

-1

它會拋出一個NullReferenceException,因爲顯然,文檔中沒有「order」元素,因此doc.Element("order")返回null。

+0

-1。不是真的 - 丹尼爾增加了秩序(作爲用戶的孩子)。搜索是錯誤的。 –

+0

@AlexeiLevenkov:我在答案中發現了什麼不正確的東西? –

+0

「沒有'訂單'」語句錯誤 - 檢查出'.Add(user);' - 用戶包含直接子訂單。問題在於「order」元素不是根元素的直接子元素,因此無法通過根元素的'Element'函數找到。 –

0

你得空引用,因爲你還沒有「秩序」作爲根元素,所以你需要的,如果你有內「用戶」,那麼你可以使用方法「元素」,而不是多個元素來做到這一點

XElement element = doc.Element("orders").Element("user").Element("order"); 
element.Add(menuelem); 

「元件」。 「Element」方法將返回第一個元素,「Elements」方法將返回XElement的IEnumerable。