語言

XAttribute.Remove 方法

定義

移除該屬性的父元素。

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

例外狀況

父元素為 null。

範例

以下範例建立一個具有三個屬性的元素。 接著它會移除其中一個屬性。

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)

此範例會產生下列輸出:

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

備註

你可以用這個方法修改 XML 樹。 此方法會引發事件發生。

有很多情況下你可能會想移除一組屬性。 在 LINQ 轉 XML 程式設計中,查詢該節點集合時,不應該操作或修改該節點集合中的節點。 實際上,這表示你不應該對一組屬性反覆修改並移除它們。 相反地,你應該用擴充方法將它們具體化成一個。List<T>ToList 然後你可以反覆修改清單,移除屬性。 欲了解更多資訊,請參閱混合宣告程式碼/命令式程式碼錯誤(LINQ 轉 XML)。

或者,如果你想移除一組屬性,建議使用此 Extensions.Remove 方法。 此方法將屬性複製到清單,然後遍歷清單,移除屬性。

適用於

另請參閱