Dave Kelly
Dave Kelly

Reputation: 129

Inserting multiple Attributes into an XML Element. LINQ SQL

I am able to get my results, but seems like there is a better way to do it.

        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);

enter image description here

Upvotes: 1

Views: 324

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134891

You could do the same by adding XAttribute items to the elements. This leaves you with more options in general as these could be dynamically generated if you needed to.

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),
});

Upvotes: 2

ocuenca
ocuenca

Reputation: 39326

Maybe saving your element references in variables to not search them every time you need to add an attribute to them:

var xml= doc.Element("XML");
xml.SetAttributeValue("Type", "ListBuilder");

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

Upvotes: 1

Related Questions