XNode.Remove 方法

定义

从节点父级中删除此节点。Removes this node from its parent.

public:
 void Remove();
public void Remove ();
member this.Remove : unit -> unit
Public Sub Remove ()

异常

父级为 nullThe parent is null.

示例

下面的示例从父节点中删除节点。The following example removes a node from its parent.

XElement xmlTree = new XElement("Root",  
    new XElement("Child1", "child1 content"),  
    new XElement("Child2", "child2 content"),  
    new XElement("Child3", "child3 content"),  
    new XElement("Child4", "child4 content"),  
    new XElement("Child5", "child5 content")  
);  
XElement child3 = xmlTree.Element("Child3");  
child3.Remove();  
Console.WriteLine(xmlTree);  
Dim xmlTree As XElement = _   
        <Root>  
            <Child1>child1 content</Child1>  
            <Child2>child2 content</Child2>  
            <Child3>child3 content</Child3>  
            <Child4>child4 content</Child4>  
            <Child5>child5 content</Child5>  
        </Root>  
  
Dim child3 As XElement = xmlTree.<Child3>(0)  
child3.Remove()  
Console.WriteLine(xmlTree)  

该示例产生下面的输出:This example produces the following output:

<Root>  
  <Child1>child1 content</Child1>  
  <Child2>child2 content</Child2>  
  <Child4>child4 content</Child4>  
  <Child5>child5 content</Child5>  
</Root>  

注解

LINQ to XMLLINQ to XML编程中,在查询集中的节点时,不应操作或修改一组节点。In LINQ to XMLLINQ to XML programming, you should not manipulate or modify a set of nodes while you are querying for nodes in that set. 在实际情况下,这意味着不应循环访问一组节点并将其删除。In practical terms, this means that you should not iterate over a set of nodes and remove them. 相反,应List<T> ToList使用扩展方法将其具体化为。Instead, you should materialize them into a List<T> by using the ToList extension method. 然后,您可以循环访问该列表以删除节点。Then, you can iterate over the list to remove the nodes. 有关详细信息,请参阅混合声明性代码/命令性代码 bug (LINQ to XML)For more information, see Mixed Declarative Code/Imperative Code Bugs (LINQ to XML).

或者,如果要删除一组节点,建议使用Extensions.Remove方法。Alternatively, if you want to remove a set of nodes, it is recommended that you use the Extensions.Remove method. 此方法将节点复制到列表,然后循环访问列表以删除节点。This method copies the nodes to a list, and then iterates over the list to remove the nodes.

此方法将引发Changed Changing和事件。This method will raise the Changed and the Changing events.

XContainer其子节点存储为XNode对象的单向链接列表。The XContainer stores its child nodes as a singly-linked list of XNode objects. 这意味着Remove该方法必须遍历父容器下直接子节点的列表。This means that the Remove method must traverse the list of direct child nodes under the parent container. 因此,使用此方法可能会影响性能。Therefore, using this method might affect your performance.

适用于

另请参阅