cannot add XAttribute into an XElement

1.1k views Asked by At

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?

1

There are 1 answers

0
dotnetstep On BEST ANSWER

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