c# - 将 XAttribute 插入到指定位置的现有 XElement

标签 c# .net xml linq linq-to-xml

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

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

        element.Add(new XAttribute("Attr2", "value2"));

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

        <Test Attr1="value1" Attr2="value2" Attr3="value3" />

感谢任何帮助。谢谢

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

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

最佳答案

我找到的唯一方法:

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

关于c# - 将 XAttribute 插入到指定位置的现有 XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17581098/

相关文章:

arrays - 带有 SimpleXMLElement 和键数组的 Twig "in"运算符

c# - 带有查询字符串错误的 Response.Redirect URL

c# - 将 Json 反序列化为 ObservableCollection

c# - 无法在 Jquery ajax 调用中发送大数据

.net - 删除.NET Framework的早期版本是否安全?

javascript - 在 XSL 中呈现 JavaScript

c# - 在 MVC 4 应用程序中使用 Unity 和 Entity Framework 的最佳实践是什么

c# - C#读取文件,方法差异

c# - 当类是变量时创建变量

xml - SAPUI5 使用 XML 文件作为 "data-sap-ui-resourceroots"的 View ?