Linq到Xml-有条件地创建XAttribute

本文关键字:创建 XAttribute 有条件 Xml- Linq | 更新日期: 2023-09-27 18:20:37

我正在使用Linq To Xml从DataSet创建Xml文件。此数据集具有具有1:M关系的Customer,Orders表。

这是我的代码片段-
如果任何当前客户订单的类型为"Online",那么我将尝试向XElement"OnlineOrder"添加几个属性。否则,如果没有"Online"类型的订单,那么我想创建一个像<OnlineOrder/>这样的空XElement。

    new XElement("OnlineOrder", ((customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(o=>o.Type=="Online").Any())
            ? customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(p1 => p1.Type == "Online").Select(
                (o1 => new XAttribute("Amount", o1.Amount)//,
                        //new XAttribute("CardType", o1.CardType),
                        //new XAttribute("Quantity", o1.Quantity)
                ))
            : null)),

上面的代码运行良好。

但是,如果我取消对添加一些额外属性的两行的注释,我会得到几个编译错误,其中一个是-

Invalid expression term ':'

请说明为什么会发生这种情况。

谢谢!

Linq到Xml-有条件地创建XAttribute

您需要提供一个属性列表。。。

new XElement("OnlineOrder", ((customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(o=>o.Type=="Online").Any())
        ? customerDT.FindByCustomerId(x.CustomerId).GetOrdersRows().Where(p1 => p1.Type == "Online").Select(
            (o1 => new List<XAttribute>() { new XAttribute("Amount", o1.Amount),
                    new XAttribute("CardType", o1.CardType),
                    new XAttribute("Quantity", o1.Quantity) }
            ))
        : null)),

顺便说一句,如果代码不那么密集,那么它将更容易跟踪/调试。为什么不把它分解成方法,或者使用局部变量呢?

请参阅本文中的Set函数:https://stackoverflow.com/a/8899367/353147

然后执行:

XElement order = new XElement("OnlineOrder");
if( your condition )
{
    Set(order, "Amount", o1.Amount, true);
    Set(order, "CardType", o1.CardType, true);
    Set(order, "Quantity", o1.Quantity, true);
}

Set通常是一个扩展方法,所以如果你知道这些并转换它,它就会变成。

XElement order = new XElement("OnlineOrder");
if( your condition )
{
    order.Set("Amount", o1.Amount, true)
         .Set("CardType", o1.CardType, true)
         .Set("Quantity", o1.Quantity, true);
}