简体   繁体   English

无法将 XAttribute 添加到 XElement

[英]cannot add XAttribute into an XElement

I want to add an attribute into an element.我想在元素中添加一个属性。 And I wish the new added attribute to be the first attribute in the element.我希望新添加的属性是元素中的第一个属性。 I used the AddFirst() , I got an error : "An attribute cannot be added to content."我使用了AddFirst() ,出现错误: "An attribute cannot be added to content." I don't know why?我不知道为什么?

the following is my codes.以下是我的代码。

XElement xmlTree = new XElement("Root",
                                new XAttribute("Att1", "content1"),
                                new XAttribute("Att2", "content2")
                            );

xmlTree.AddFirst(new XAttribute("test", "testAttr"));

Any other way allows me to add an attribute as a first attribute in the element?任何其他方式允许我添加一个属性作为元素中的第一个属性?

This will solve your problem.这将解决您的问题。 AddFirst can not be use in this case.在这种情况下不能使用 AddFirst。

XElement xmlTree = new XElement("Root",
                                new XAttribute("Att1", "content1"),
                                new XAttribute("Att2", "content2")
                            );

var attributes = xmlTree.Attributes().ToList();
attributes.Insert(0, new XAttribute("test", "testAttr"));
xmlTree.ReplaceAttributes(attributes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM