如何使用Linq-xml在Xelement内部的确定位置设置属性值



我需要为一个大约有10个属性的xml节点添加一个新属性。使用以下命令将属性添加到元素属性列表的末尾。

*identityVerificationManagerServiceNode.SetAttributeValue("PresetID", "24761685-715F-40F3-8FDA-5C2E372A1186");*

我不希望它走到最后,我需要它在XName为"的属性之后;定义ID";。有没有一种方法可以使用Linq将元素内部的属性顺序更改为XML?

使用XLinq:可以轻松完成属性排序

static void Main(string[] args)
{
XElement xe1 = XElement.Parse(@"<root><some-element a = '1' c = '3' b = '2' d = '4' e = '5' g = '6' h = '7'/></root>");
XElement xe2 = new XElement("root");
foreach (XElement xe in xe1.Elements()){
xe2.Add(new XElement(xe.Name.LocalName, xe.Attributes().Select(c => c).OrderBy(c => c.Name.LocalName)));
}
Console.Write("unordered-->n");
Console.Write(xe1.ToString());
Console.Write("nnordered-->n");
Console.Write(xe2.ToString());
Console.ReadKey();
}

最新更新