XAttribute.Remove 方法

定義

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

public:
 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");  
att.Remove();  
Console.WriteLine(root);  
Dim root As XElement = <Root Att1="content1" Att2="content2" Att3="content3"/>  
Dim att As XAttribute = root.Attribute("Att2")  
att.Remove()  
Console.WriteLine(root)  

這個範例會產生下列輸出: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 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 attributes and remove them. 相反地, 您應該List<T> ToList使用擴充方法, 將它們具體化成。Instead, 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.

適用於

另請參閱