2016-09-21 65 views
0

這裏是一段代碼,我試圖將一個整數列表嵌入到XML中。XML變量不填充在C#

function(long[] Idlist) 
{ 
XDocument inputXML = new XDocument(
      new XElement("Ids", 
         from wp in Idlist 
         select new XElement("element"))); 
} 

我有我的IdList [20,30,40,50]中的四個值,但仍然輸入xml不填充任何值。

和inputXML填充像這樣:

<Ids> 
    <element/> 
    <element/> 
    <element/> 
    <element/> 
</Ids> 

有什麼建議?

+0

我建議你來填充,而不是像'新的XElement(「元素」)'空元素與具有值的元素的XAML。 –

+0

感謝您的回覆。這些值將從Idlist中獲取,我相信。它不應該填充XML嗎?你能舉個例子嗎? – user3842125

+0

你爲什麼認爲它知道你想要什麼? –

回答

0

你的查詢看起來像:

from wp in Idlist 
select new XElement("element") 

您使用的不是從你的Idlist任何數據送入XElement

您已經使用了this constructor,它使用您提供的名稱創建了一個空元素。

嘗試使用the correct constructor,它允許您傳入XElement的值以及名稱。

1

編譯器無法知道您希望wp以某種方式包含在XML中。如果你想要發生什麼,你必須要好好問。

XDocument inputXML = new XDocument(
    new XElement("Ids", 
     from wp in Idlist 
     // XElement has another constructor which takes a second 
     // parameter, and uses that as the content of the element. 
     select new XElement("element", wp) 
     )); 

XML

<Ids> 
    <element>20</element> 
    <element>30</element> 
    <element>40</element> 
    <element>50</element> 
</Ids> 
+0

謝謝。會試試這個。 – user3842125

-1

在VB.NET中這會工作

Dim xe As XElement = <Ids></Ids> 
    Dim IdList As New List(Of Integer) From {20, 30, 40, 50} 
    For Each id As Integer In IdList 
     Dim els As XElement = <element><%= id %></element> 
     xe.Add(New XElement(els)) 
    Next