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