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 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.

適用於

另請參閱