XML 未在 C# 中填充变量

XML variable not populated in c#

这是一段代码,我试图将整数列表嵌入到 XML。

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

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

AND 输入XML 填充如下:

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

有什么建议吗?

编译器无法知道您希望 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>

您的查询如下:

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

您没有使用 Idlist 中的任何数据输入 XElement

您使用了 this constructor,它使用您提供的名称创建了一个空元素。

尝试使用 the correct constructor,它允许您传入 XElement 的值以及名称。

在 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