XmlElement.SetAttributeNode Method

Definition

Adds a new XmlAttribute.

Overloads

SetAttributeNode(XmlAttribute)

Source:
XmlElement.cs
Source:
XmlElement.cs
Source:
XmlElement.cs

Adds the specified XmlAttribute.

C#
public virtual System.Xml.XmlAttribute SetAttributeNode(System.Xml.XmlAttribute newAttr);
C#
public virtual System.Xml.XmlAttribute? SetAttributeNode(System.Xml.XmlAttribute newAttr);

Parameters

newAttr
XmlAttribute

The XmlAttribute node to add to the attribute collection for this element.

Returns

If the attribute replaces an existing attribute with the same name, the old XmlAttribute is returned; otherwise, null is returned.

Exceptions

The newAttr was created from a different document than the one that created this node. Or this node is read-only.

The newAttr is already an attribute of another XmlElement object. You must explicitly clone XmlAttribute nodes to re-use them in other XmlElement objects.

Remarks

If an attribute with that name is already present in the element, it is replaced by the new one.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

SetAttributeNode(String, String)

Source:
XmlElement.cs
Source:
XmlElement.cs
Source:
XmlElement.cs

Adds the specified XmlAttribute.

C#
public virtual System.Xml.XmlAttribute SetAttributeNode(string localName, string namespaceURI);
C#
public virtual System.Xml.XmlAttribute SetAttributeNode(string localName, string? namespaceURI);

Parameters

localName
String

The local name of the attribute.

namespaceURI
String

The namespace URI of the attribute.

Returns

The XmlAttribute to add.

Examples

The following example adds an attribute to an element.

C#
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {

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

    XmlElement root = doc.DocumentElement;

    // Add a new attribute.
    XmlAttribute attr = root.SetAttributeNode("genre", "urn:samples");
    attr.Value="novel";

    Console.WriteLine("Display the modified XML...");
    Console.WriteLine(doc.InnerXml);
  }
}

Remarks

The XmlAttribute does not have any children. Use Value to assign a text value to the attribute or use AppendChild (or a similar method) to add children to the attribute.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0