【问题标题】:Using Linq to XML foreach to create muliple XElements使用 Linq to XML foreach 创建多个 XElement
【发布时间】:2013-09-05 10:28:03
【问题描述】:

我正在使用新的XElement() 动态构建一个 XML 文件,在文件创建的中途,我需要遍历一组子记录并为它们创建 XElements。我遇到的问题是每次迭代需要创建超过 1 个XElement。这是我的循环:

from t in trans.SalesTransactionLines
select new XElement("text", new XAttribute("lang", "en"), t.ItemName)

这很好用,但我需要在每个“文本”元素之前添加一个额外的“位置”XElement。这是我想要的那种东西,它不起作用:

from t in trans.SalesTransactionLines
select new XElement("position",new XAttribute("x", "40"), new XAttribute("y", "420")),
new XElement("text", new XAttribute("lang", "en"), t.ItemName)

这是我正在寻找的结果:

<position x="40" y="420" />
<text>Fender Classic Strat 70s Natural RN</text>
<position x="40" y="420" />
<text>Fender Classic 50s Tele White Blonde</text>

【问题讨论】:

    标签: asp.net-mvc-4 foreach linq-to-xml xelement


    【解决方案1】:

    改用基于方法的语法和SelectMany 方法:

    trans.SalesTransactionLines.SelectMany(x => new[] {
                                                    new XElement("position",
                                                        new XAttribute("x", "40"),
                                                        new XAttribute("y", 420")),
                                                    new XElement("text",
                                                        new XAttribute("lang", "en"),
                                                        x.ItemName)
    })
    

    【讨论】:

    • 这看起来像我需要的,但't'来自哪里?
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多