---
title: Copying an XmlNode Between XmlValue Variables
slug: copying-an-xmlnode-between-xmlvalue-variables
createdAt: 2026-06-11T23:14:33.603Z
---

## Overview

You can copy an `XmlNode` between `XmlValue` variables by cloning the source node and assigning the cloned node to the target value.

## Use Case

Use this approach when you need to transfer a list, nested structure, or other XML fragment from one object to another without rebuilding the XML manually.

## Example

```csharp
using System.Xml;

// Instantiate a service instance and add some test data.
// This will be our source for the copy.
ServiceInstance srv1 = new ServiceInstance();
srv1.Data.SetValue("selectedItems/@list", "1");
srv1.Data.AddListValue("selectedItems/item", "item1");
srv1.Data.AddListValue("selectedItems/item", "item2");

// Instantiate a service instance.
// This will be the target for our copy.
ServiceInstance srv2 = new ServiceInstance();

// Trace before the copy.
Trace.WriteLine(srv2.Data.FormattedXml);

// Select the node to copy.
XmlNode sourceNode = srv1.Data.SelectSingleNode("selectedItems");

// Clone the source node and set it into the target.
srv2.Data.SetValue("selectedItems", sourceNode.CloneNode(true));

// Trace after the copy.
Trace.WriteLine(srv2.Data.FormattedXml);
```

## How It Works

1. Create or retrieve the source XML structure.
2. Select the node to be copied using `SelectSingleNode()`.
3. Clone the node using `CloneNode(true)`.
4. Assign the cloned node to the target using `SetValue()`.
5. The target now contains an independent copy of the original XML structure.

## Result

Before the copy, the target contains no `selectedItems` node.

After the copy, the target contains:

```xml
<selectedItems list="1">
  <item>item1</item>
  <item>item2</item>
</selectedItems>
```

## Key Points

- `CloneNode(true)` performs a deep copy, including all child nodes and attributes.
- The source and target become independent after the copy.
- Changes made to the target node do not affect the original source node.
- This technique is useful for copying lists, collections, and complex XML structures between objects.

## Notes

- Use `CloneNode(true)` when you want to preserve the entire XML hierarchy.
- A shallow clone (`CloneNode(false)`) copies only the selected node and excludes child nodes.
- This approach avoids manually recreating XML structures in the target object.
