XNode.Remove 方法

定義

將這個節點從其父代 (Parent) 移除。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 XML 程式設計中,您不應該在查詢該集合中的節點時,操作或修改一組節點。In LINQ 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> 使用擴充方法將它們具體化為 ToListInstead, 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 節點儲存為物件的單一連結清單 XNodeThe 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.

適用於