sept. 30

Regularly, you would manipulate several XmlDocument and you may need to select some XmlNode to copy / move them to another one.

Let's illustrate this behavior by a test.

[TestMethod]
public void TestMethod1()
{
   string xml = @"
         <myNode attribute=""MyAttributeValue"">
            <myChildNode />
         </myNode>
   ";
   /*Code ignored : this method will just put the XML 
    * in a single line like : 
    * <myNode attribute=""MyAttributeValue""><...
    */
   string xmlStripped = StripXml(xml);
 
   //1. Let's load the Source XmlDocument
   XmlDocument domSource = new XmlDocument();
   domSource.LoadXml(xmlStripped);
   Assert.AreEqual(xmlStripped, domSource.OuterXml);
 
   //2. Let's select a node
   XmlNode node = domSource.SelectSingleNode("myNode");
 
   //3. Copy it !
   XmlDocument domTarget = new XmlDocument();
   CopyTo(domTarget, node);
   Assert.AreEqual(xmlStripped, domTarget.OuterXml);
}

How could we code the CopyTo method ? Let's do that simply :

/// <summary>
/// Copy a node from a source XmlDocument to a target XmlDocument
/// </summary>
/// <param name="domTarget">The XmlDocument to which we want to copy</param>
/// <param name="node">The node we want to copy</param>
private void CopyTo(XmlDocument domTarget, XmlNode node)
{
   domTarget.AppendChild(node);
}

Too simple maybe, it fails with the following exception : "The node to be inserted is from a different context"

Why ? Simple in fact. Each XmlNode belongs to an XmlDocument and they simply cannot be moved like that. Let's try another implementation :

/// <summary>
/// Copy a node from a source XmlDocument to a target XmlDocument
/// </summary>
/// <param name="domTarget">The XmlDocument to which we want to copy</param>
/// <param name="node">The node we want to copy</param>
private void CopyTo(XmlDocument domTarget, XmlNode node)
{
   XmlNode nodeToMove = domTarget.ImportNode(node, true);
   domTarget.AppendChild(nodeToMove);
}

There is no extra things to do, you don't need to implement your own Copy method ! (Note that this behavior exist since .NET 1.0) Note also that if you manipulate an XmlNode and not an XmlDocument, you can just access the XmlDocument to which the node belongs to, by using the OwnerDocument property.

Tags: | |

Commentaires

Ajouter un commentaire




biuquote
  • Commentaire
  • Aperçu immédiat
Loading