I noticed that XElement
is a class, so I tried something like:
var doc = new XDocument(
new XDeclaration("1.0", "utf8", "yes"),
new XElement("Root")
);
var root = doc.Root;
var com = new XElement("Component", new XAttribute("name", "arm"));
root.Add(com);
root.Add(com);
root.Add(com);
com.Add(new XAttribute("type", 1));
Console.WriteLine(doc);
but the output is:
<Root>
<Component name="arm" type="1" />
<Component name="arm" />
<Component name="arm" />
</Root>
I also tried SetAttributeValue()
, and got the same result.
Why is the type attribute only attached to the first component?
The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.
An element has an XName, optionally one or more attributes, and can optionally contain content (for more information, see Nodes ). An XElement can contain the following types of content:
This class represents an XML element, the fundamental XML construct. See XElement Class Overview for other usage information. An element has an XName, optionally one or more attributes, and can optionally contain content (for more information, see Nodes ). An XElement can contain the following types of content:
Initializes a new instance of the XElement class with the specified name and content. Initializes a new instance of the XElement class with the specified name and content. Initializes a new instance of the XElement class from an XStreamingElement object.
Asynchronously creates a new XElement and initializes its underlying XML tree using the specified stream, optionally preserving white space. Asynchronously creates a new XElement and initializes its underlying XML tree using the specified text reader, optionally preserving white space.
My original answer stands (essentially "by design") and here is a reason why...
From MS Documentation (and following the relevant links) you will find that
XElement
inherits XContainer
inherits XNode
XContainer
has method Add()
and properties FirstNode
and LastNode
XNode
has properties NextNode
and PreviousNode
If Add()
blindly added references to the same object without creating copies where necessary to avoid multiple-referencing, how could circular references be avoided? In your example above, FirstNode
and FirstNode.NextNode
would reference the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With