简体   繁体   English

将XDocument.Root添加到另一个无法正常工作的XElement

[英]Add XDocument.Root to another XElement non working as expected

so I'm doing some xml manipulation and I've found myself in a strange situation. 所以我正在做一些xml操作,但发现自己处在一种奇怪的情况下。 After adding an XElement with null Parent to another XElement I still had the Parent set to null. 将具有null Parent的XElement添加到另一个XElement之后,我仍然将Parent设置为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. 看来,当您添加一个XElement作为XDocument的根时,该XElement将被复制,并且您需要在添加之前调用Remove。 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. 该文档说,当Parent为null时,Remove应该引发异常,但是在这种情况下,它似乎正在删除XDocument及其根之间的关系。 Is this interpration correct or is there another explanation? 这种插入是正确的还是有其他解释?

The word parent does not mean the same thing with respect to the XObject.Parent property and the XNode.Remove() method. 关于XObject.Parent属性和XNode.Remove()方法,“父”一词的含义不同。

In the case of the XObject.Parent property, it is returning the parent XElement of the XObject. 对于XObject.Parent属性,它将返回XObject的父XElement。 So if the parent of the XObject is not of type XElement, it will return null. 因此,如果XObject的父级不是XElement类型,则它将返回null。 In your example, the "asd" node DOES have a parent, but since it is of type XDocument instead of XElement, it returns null. 在您的示例中,“ asd”节点确实有一个父节点,但是由于它是XDocument类型而不是XElement类型,因此它返回null。

The XNode.Remove method removes an XNode object from its' parent. XNode.Remove方法从其父级移除XNode对象。 For example it works with any type which inherits from XNode. 例如,它适用于从XNode继承的任何类型。

    XElement node1 = new XElement("node1");
    XComment comment1 = new XComment("comment1");
    node1.Add(comment1);
    comment1.Remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM