Here is simplified use case code example for creating element with attributes
        XElement element =
            new XElement(
                "Test",
                new XAttribute("Attr1", "value1"),
                new XAttribute("Attr3", "value3")
            );
        element.Add(new XAttribute("Attr2", "value2"));
How to achieve that Attr2 is added after Attr1 to produce output like this?
        <Test Attr1="value1" Attr2="value2" Attr3="value3" />
Any help is appreciated. Thank you
Here is the extension method mentioned in accepted answer:
public static void AddAfterSelf(this XAttribute self, XAttribute value)
{
    if (self == null) throw new ArgumentNullException("self");
    if (value == null) throw new ArgumentNullException("value");
    if (self.Parent == null) throw new ArgumentException("Attribute does not belong to any element.");
    XElement e = self.Parent;
    var attributes = new List<XAttribute>(e.Attributes());
    int idx = attributes.IndexOf(self);
    attributes.Insert(idx + 1, value);
    e.RemoveAttributes();
    e.Add(attributes);
}
                The only way I have found:
var attributes = element.Attributes().ToList();
attributes.Insert(1, new XAttribute("Attr2", "value2"));
element.Attributes().Remove();
element.Add(attributes);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With