Calendar

<<  mars 2010  >>
lumamejevesadi
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

(septembre 30, 2008 09:12)

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.

Billets liés

Ajouter un commentaire


 

  Country flag





Live preview

mars 10. 2010 15:30

Powered by BlogEngine.NET 1.2.0.0 | Theme by Pierre-Emmanuel Dautreppe