1

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." 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?

kennyzx
  • 12,845
  • 6
  • 39
  • 83
peter
  • 1,009
  • 3
  • 15
  • 23
  • `AddFirst` is adding a `child` to element, not attribute. And by the way, the order of attribute specifications in a start-tag or empty-element tag is not significant, meaning you can append the new attribute to the end of the attribute list and XML parser will treat both cases indifferently. – kennyzx Dec 23 '14 at 05:40

1 Answers1

2

This will solve your problem. AddFirst can not be use in this case.

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);
Bondolin
  • 2,793
  • 7
  • 34
  • 62
dotnetstep
  • 17,065
  • 5
  • 54
  • 72