XmlAttributeCollection.SetNamedItem(XmlNode) 方法

定義

使用其 XmlNode 屬性新增 Name

public:
 override System::Xml::XmlNode ^ SetNamedItem(System::Xml::XmlNode ^ node);
public override System.Xml.XmlNode SetNamedItem (System.Xml.XmlNode node);
public override System.Xml.XmlNode? SetNamedItem (System.Xml.XmlNode? node);
override this.SetNamedItem : System.Xml.XmlNode -> System.Xml.XmlNode
Public Overrides Function SetNamedItem (node As XmlNode) As XmlNode

參數

node
XmlNode

儲存在這個集合中的屬性節點。 這個節點稍後可用節點名稱來存取。 如果集合中已經有這個名稱的節點,它將會被新的節點取代;否則,這個節點就會附加在集合的結尾。

傳回

如果 node 取代同名的現有節點,則傳回舊節點;否則傳回所加入的節點。

例外狀況

node 由不同於建立這個集合的另一個 XmlDocument 所建立。

這個 XmlAttributeCollection 是唯讀的。

node 是已經成為另一個 XmlAttribute 物件屬性的 XmlElement。 若要重複使用其他項目中的屬性,您必須複製 (Clone) 想要重複使用的 XmlAttribute 物件。

範例

下列範例會將新的屬性新增至檔。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" );
   
   //Create a new attribute.
   XmlAttribute^ newAttr = doc->CreateAttribute( "genre" );
   newAttr->Value = "novel";
   
   //Create an attribute collection and add the new attribute
   //to the collection.
   XmlAttributeCollection^ attrColl = doc->DocumentElement->Attributes;
   attrColl->SetNamedItem( newAttr );
   Console::WriteLine( "Display the modified XML...\r\n" );
   Console::WriteLine( doc->OuterXml );
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main(){

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Create a new attribute.
    XmlAttribute newAttr = doc.CreateAttribute("genre");
    newAttr.Value = "novel";

    //Create an attribute collection and add the new attribute
    //to the collection.
    XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;
    attrColl.SetNamedItem(newAttr);

    Console.WriteLine("Display the modified XML...\r\n");
    Console.WriteLine(doc.OuterXml);
  }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()
  
    Dim doc as XmlDocument = new XmlDocument()
    doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                "<title>Pride And Prejudice</title>" & _
                "</book>")      

    'Create a new attribute.
    Dim newAttr as XmlAttribute = doc.CreateAttribute("genre")
    newAttr.Value = "novel"

    'Create an attribute collection and add the new attribute
    'to the collection.  
    Dim attrColl as XmlAttributeCollection = doc.DocumentElement.Attributes
    attrColl.SetNamedItem(newAttr)

    Console.WriteLine("Display the modified XML...")
    Console.WriteLine(doc.OuterXml)

  end sub
end class

適用於