【问题标题】:Inserting multiple Attributes into an XML Element. LINQ SQL将多个属性插入 XML 元素。 LINQ SQL
【发布时间】:2016-02-23 19:19:36
【问题描述】:

我能够得到我的结果,但似乎有更好的方法。

        doc.Element("XML").SetAttributeValue("Type", "ListBuilder");
        doc.Element("XML")
           .Element("Order").SetAttributeValue("No", 425654);
        doc.Element("XML")
           .Element("Order").SetAttributeValue("DispDate", today);
        doc.Element("XML")
           .Element("Order").SetAttributeValue("Basket", 3536);

【问题讨论】:

    标签: c# linq linq-to-xml


    【解决方案1】:

    您可以通过将XAttribute 项目添加到元素来执行相同的操作。一般来说,这为您提供了更多选项,因为如果您需要,这些选项可以动态生成。

    doc.Element("XML").Add(new XAttribute("Type", "ListBuilder"));
    doc.Element("XML").Element("Order").Add(new[]
    {
        new XAttribute("No", 425654),
        new XAttribute("DispDate", today),
        new XAttribute("Basket", 3536),
    });
    

    【讨论】:

    • 我完全忘记了 Add 方法可以添加任何类型的内容。我完全支持这个答案。
    【解决方案2】:

    也许将元素引用保存在变量中,以便在每次需要向它们添加属性时不搜索它们:

    var xml= doc.Element("XML");
    xml.SetAttributeValue("Type", "ListBuilder");
    
    var order=xml.Element("Order");
    order.SetAttributeValue("No", 425654);
    //...
    

    【讨论】:

    • 那肯定比我拥有的要好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多