XAttribute.Remove 方法


將這個屬性從其父項目移除。Removes this attribute from its parent element.

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


父元素是 nullThe parent element is null.


下列範例會建立具有三個屬性的元素。The following example creates an element with three attributes. 然後,它會移除其中一個屬性。It then removes one of the attributes.

XElement root = new XElement("Root",  
    new XAttribute("Att1", "content1"),  
    new XAttribute("Att2", "content2"),  
    new XAttribute("Att3", "content3")  
XAttribute att = root.Attribute("Att2");  
Dim root As XElement = <Root Att1="content1" Att2="content2" Att3="content3"/>  
Dim att As XAttribute = root.Attribute("Att2")  

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

<Root Att1="content1" Att3="content3" />  


您可以使用這個方法來修改 XML 樹狀結構。You can use this method to modify an XML tree. 這個方法會導致事件發生。This method will cause events to occur.

在許多情況下,您可能會想要移除一組屬性。There are many scenarios in which you might want to remove a set of attributes. 在 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 attributes and remove them. 相反地,您應該 List<T> 使用擴充方法將它們具體化為 ToListInstead, you should materialize them into a List<T> using the ToList extension method. 然後,您可以反復查看清單,移除屬性。Then you can iterate over the list, removing the attributes. 如需詳細資訊,請參閱混合的宣告式程式 代碼/命令式程式碼 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 attributes, it is recommended that you use the Extensions.Remove method. 這個方法會將屬性複製到清單,然後逐一查看清單,移除屬性。This method copies the attributes to a list, then iterates over the list, removing the attributes.