Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does XElement not behave like a reference type?

Tags:

c#

xml

linq

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?

like image 224
Obsidian Avatar asked May 31 '21 10:05

Obsidian


People also ask

What is XElement C#?

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.

What is the difference between xname and XElement?

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:

What is an XElement class?

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:

What is initialize in Java XElement?

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.

What is asynchronously created XElement?

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.


1 Answers

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.

like image 113
AlanK Avatar answered Oct 11 '22 16:10

AlanK