c# - 在 C# 中将列表转换为 xml

标签 c# asp.net xml list

我有一个字符串列表。我需要将它转换成 xml 文档。我正在使用 XElement 来实现这一目标。

   List<string> list= myString.Split(',').ToList();

  XElement xmlElements = new XElement("Root", new XElement("Number",list.Select(i => new XElement("Num", i)))); 
               System.Console.Write(xmlElements);
               System.Console.Read();

我得到以下格式。

<Root>
 <Number>
  <Num></Num>
 <Num></Num>
 </Number>
</Root>

但我需要这样的东西。

 <Root>
  <Number id=1>
    <Num></Num>
  </Number>
 <Number id=2>
   <Num></Num>
 </Number>
</Root>

如何实现。

最佳答案

如果 id 是指索引,则:

XElement xmlElements = 
    new XElement("Root",        
        list.Select((i, index) => new XElement("Number", 
                                      new XAttribute("id", index),
                                      new XElement("Num", i))));

“a,b,c”的结果将是

<Root>
  <Number id="0">
    <Num>a</Num>
  </Number>
  <Number id="1">
    <Num>b</Num>
  </Number>
  <Number id="2">
    <Num>c</Num>
  </Number>
</Root>

关于c# - 在 C# 中将列表转换为 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28672080/

相关文章:

c# - Asp.Net MVC C# 无法隐式转换类型问题

c# - 波浪号 (~) 字符在这里做什么

c# - 相交和任何或包含和任何。找到至少一个公共(public)元素哪个更有效?

c# - GridView 检索每一行中的数据

javascript - 使用显示 :none 时如何显示 Div

c# - LINQ : Get attribute with any namespace but specific name

c# - 无效操作异常 : The Undo operation encountered a context that is different from what was applied in the corresponding Set operation

asp.net - 如何在 ASP.Net GridView 中为 AutoGenerateEditButton 使用图像而不是文本

html - XPath根据标签选择表格单元格?

C# - 来自 XML 的数组作为嵌入式资源