Sergey
Sergey

Reputation: 1660

Is there a way to duplicate or make another copy of an XmlNodeList in C#?

I load an XmlDocument and then select some nodes into an XmlNodeList instance. If I edit any of those nodes, the XmlDocument will be modified

XmlDocument xd = loadXml();
XmlNodeList xnl = xd.SelectNodes("/root/nodes");

foreach (XmlNode n in xnl)
{
    n.InnerText = "";
}

So I understand that modifying the XmlNodeList - modifies the XmlDocument that the node list was taken from.

Is there some way to create a deep copy (I think that's what I need) of the list of nodes into another XmlElement, so that when I modify these nodes they will be independent of the original location where they were copied from?

Upvotes: 3

Views: 6849

Answers (2)

Juan Ayala
Juan Ayala

Reputation: 3518

There is more than one way to skin an xml cat. This is just one.

    var xd = new XmlDocument();
    xd.LoadXml("<root><nodes><node>1</node><node>2</node></nodes></root>");
    var xnl = xd.SelectSingleNode("/root/nodes").Clone();

    foreach (XmlNode n in xnl)
    {
        n.InnerText = "x";
    }

    Console.Out.WriteLine(xd.OuterXml);
    Console.Out.WriteLine("--------------");
    Console.Out.WriteLine(xnl.OuterXml);

Upvotes: 3

Ryan
Ryan

Reputation: 28207

You would need to create your own copies using .CloneNode. MSDN has an example.

Upvotes: 1

Related Questions