将XAttribute插入指定位置的现有XElement

Yak*_*een 5 .net c# xml linq linq-to-xml

以下是用于创建具有属性的元素的简化用例代码示例

        XElement element =
            new XElement(
                "Test",
                new XAttribute("Attr1", "value1"),
                new XAttribute("Attr3", "value3")
            );

        element.Add(new XAttribute("Attr2", "value2"));
Run Code Online (Sandbox Code Playgroud)

如何实现在Attr1之后添加Attr2以产生这样的输出?

        <Test Attr1="value1" Attr2="value2" Attr3="value3" />
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.谢谢

这是接受的答案中提到的扩展方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

Yur*_*pka 9

我找到的唯一方法:

var attributes = element.Attributes().ToList();
attributes.Insert(1, new XAttribute("Attr2", "value2"));
element.Attributes().Remove();
element.Add(attributes);
Run Code Online (Sandbox Code Playgroud)