Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

XmlNode.ReplaceChild Method

Replaces the child node oldChild with newChild node.

Namespace:  System.Xml
Assembly:  System.Xml (in System.Xml.dll)
public virtual XmlNode ReplaceChild(
	XmlNode newChild,
	XmlNode oldChild
)

Parameters

newChild
Type: System.Xml.XmlNode

The new node to put in the child list.

oldChild
Type: System.Xml.XmlNode

The node being replaced in the list.

Return Value

Type: System.Xml.XmlNode
The node replaced.
ExceptionCondition
InvalidOperationException

This node is of a type that does not allow child nodes of the type of the newChild node.

The newChild is an ancestor of this node.

ArgumentException

The newChild was created from a different document than the one that created this node.

This node is read-only.

The oldChild is not a child of this node.

If the newChild is already in the tree, it is first removed.

If the newChild was created from another document, you can use XmlDocument.ImportNode to import the node to the current document. The imported node can then be passed to the ReplaceChild method.

Notes to Inheritors

When overriding ReplaceChild in a derived class, in order for events to be raised correctly, you must call the ReplaceChild method of the base class.

The following example replaces the title element in the XML document.

using System;
using System.IO;
using System.Xml;

public class Sample {

  public static void Main() {

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

    XmlNode root = doc.DocumentElement;

    //Create a new title element.
    XmlElement elem = doc.CreateElement("title");
    elem.InnerText="The Handmaid's Tale";

    //Replace the title element.
    root.ReplaceChild(elem, root.FirstChild);

    Console.WriteLine("Display the modified XML...");
    doc.Save(Console.Out);

  }
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft. All rights reserved.