LINQ to XML Cloning

Can someone explain why the source address of the XElement street node is changing? It appears that client1 has a link to the XElement address, but client2 and client3 made copies.

Why did the source address change? (LINQPad example)

var address =
    new XElement ("address",
        new XElement ("street", "Lawley St"), 
        new XElement ("town", "North Beach")
    );

var customer1 = new XElement ("customer1", address);
var customer2 = new XElement ("customer2", address);
var customer3 = new XElement ("customer3", address);

customer1.Element ("address").Element ("street").Value = "Another St";

Console.WriteLine (customer2.Element ("address").Element ("street").Value);
Console.WriteLine ();

address.Dump();
Console.WriteLine ();

customer1.Dump();
Console.WriteLine ();

customer2.Dump();
Console.WriteLine ();

customer3.Dump();

OUTPUT

Lawley St


<address>
  <street>Another St</street>
  <town>North Beach</town>
</address> 


<customer1>
  <address>
    <street>Another St</street>
    <town>North Beach</town>
  </address>
</customer1> 


<customer2>
  <address>
    <street>Lawley St</street>
    <town>North Beach</town>
  </address>
</customer2> 


<customer3>
  <address>
    <street>Lawley St</street>
    <town>North Beach</town>
  </address>
</customer3> 
+3
source share
2 answers

The same XElement cannot be in multiple trees. Of course, you can have multiple references to the same XElement in a particular tree, but the same XElement cannot be in multiple trees .

customer1 , address XElement. , customer2, address1 XElement , node XElement. address node, XElement XElement customer2 customer3. "" XElements.

+1

:

, customer1 XElement, 2 3 .

, , . docs XElement:

XNode XAttribute , , XML. XML, , XML .

address , . , .

+8

Source: https://habr.com/ru/post/1740919/


All Articles