0

so I'm doing some xml manipulation and I've found myself in a strange situation. After adding an XElement with null Parent to another XElement I still had the Parent set to null. So after some testing I've fond the problem, but I don't clearly understand the behaviour.

XDocument x=new XDocument(new XElement("asd"));
XElement root=x.Root;
XElement parent=new XElement("parent");
Console.WriteLine(root.Parent?.Name??"null"); //still null
parent.Add(root);
Console.WriteLine(root.Parent?.Name??"null"); //should be 
root.Remove(); // should throw InvalidOperationException
parent.Add(root);
Console.WriteLine(root.Parent?.Name??"null");//parent

It seems that when you add an XElement that is the Root of a XDocument the XElement is copied and you need to call Remove before adding. The documentation says that Remove should throw exception when Parent is null, but instead in this case it seems that it is removing the relation between the XDocument and its root. Is this interpration correct or is there another explanation?

  • Also beware of automatic deep cloning. Say, you have: `var address = new XElement("address", new XElement("street", "1-st Avenue"));` Then, if you add this element to different `XElement`s, these elements will have two different addresses: `var worker = new XElement("worker1", address); var worker1 = new XElement("worker2", address); worker1.Element("address").Element("street"). Value = "2-nd South"; Console.WriteLine(worker2.Element("address").Element("street").Value); //Prints "1-st Avenue"` – JohnyL May 08 '18 at 21:17

1 Answers1

0

The word parent does not mean the same thing with respect to the XObject.Parent property and the XNode.Remove() method.

In the case of the XObject.Parent property, it is returning the parent XElement of the XObject. So if the parent of the XObject is not of type XElement, it will return null. In your example, the "asd" node DOES have a parent, but since it is of type XDocument instead of XElement, it returns null.

The XNode.Remove method removes an XNode object from its' parent. For example it works with any type which inherits from XNode.

    XElement node1 = new XElement("node1");
    XComment comment1 = new XComment("comment1");
    node1.Add(comment1);
    comment1.Remove();
Ehz
  • 2,027
  • 1
  • 12
  • 11
  • Oh right I didn't notice this, but I still think this is strange because both XDocument and XElement are XObjects so I don't understand why Parent is an XElement. I mean, take my example, is there any way to know the the XElement has a Parent that isn't another XElement? – alessio bortolato May 09 '18 at 09:03