XNode.Remove 方法


將這個節點從其父代 (Parent) 移除。Removes this node from its parent.

 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");  
Dim xmlTree As XElement = _   
            <Child1>child1 content</Child1>  
            <Child2>child2 content</Child2>  
            <Child3>child3 content</Child3>  
            <Child4>child4 content</Child4>  
            <Child5>child5 content</Child5>  
Dim child3 As XElement = xmlTree.<Child3>(0)  

這個範例會產生下列輸出:This example produces the following output:

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


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. 相反地,您應該使用 ToList 擴充方法,將它們具體化為 List<T>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.

這個方法會引發 ChangedChanging 的事件。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.