Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert XAttribute to existing XElement at specified position

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);
}
like image 978
Yakeen Avatar asked Jul 10 '13 21:07

Yakeen


1 Answers

The only way I have found:

var attributes = element.Attributes().ToList();
attributes.Insert(1, new XAttribute("Attr2", "value2"));
element.Attributes().Remove();
element.Add(attributes);
like image 71
Yuriy Rypka Avatar answered Nov 12 '22 21:11

Yuriy Rypka