【问题标题】:Write xmlelement using LINQ C#使用 LINQ C# 编写 xmlelement
【发布时间】:2015-11-28 15:35:52
【问题描述】:

如何使用 LINQ 将以下内容转换为 xml

List<int> calllist = new List<int>();
calllist.Add(10);
calllist.Add(5);
calllist.Add(1);
calllist.Add(20);

输出应该是:

<root>
    <child>
        <name>1</name>
        <count>1</count>
    </child>
    <child>
        <name>5</name>
        <count>1</count>
    </child>
    <child>
        <name>10</name>
        <count>1</count>
    </child>
    <child>
        <name>20</name>
        <count>1</count>
    </child>
</root>

我尝试了类似的方法:

XElement root = new XElement ("root", 
    new XElement("child",new XElement(from c in calllist select c; /*error here*/ )));

但是卡住了,无法继续。谁能分享一个解决方案来完成这项工作?

【问题讨论】:

  • 有一个完整的命名空间专用于使用 LINQ to XML,阅读msdn.microsoft.com/en-us/library/bb387061.aspx
  • XmlElementXmlAttribute 来自旧的 DOM API。对于 LINQ to XML,您希望 XElementXAttribute 以...开头。
  • @JonSkeet 谢谢你。我导入了 Xml.Linq 并更新了帖子。
  • 对,现在你为什么要使用XAttribute?您认为您的示例 XML 中有哪些属性?想想你想要多少 child 元素 - 每个条目一个,对吧? (您可以稍后考虑计数)。所以这应该是查询的一部分......
  • 我明白了。我这里不需要 xattribute。

标签: c# linq linq-to-xml


【解决方案1】:

@user833985

试试下面的。

XElement root = new XElement(
            "root", from c in calllist orderby c select
            new XElement("child", 
                 new XElement("name", c),
                  new XElement("count",calllist.Count))

            );

【讨论】:

  • 这不会让每个“count”元素都有 4 作为内容吗?我不确定这个问题应该有什么,但我怀疑 4 是否正确。我想你想按 c 分组,然后使用组的计数——但从问题中并不清楚。
【解决方案2】:
XElement root = 
  new XElement("root",
    calllist
      .GroupBy(c => c)
      .OrderBy(g => g.Key)
      .Select(g => new XElement("child",
                                new XElement("name", g.Key),
                                new XElement("count",g.Count())
                               )
             )
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    相关资源
    最近更新 更多