Cloning a XmlNode #

After reading Bob Brumfield’s post about his issue with selecting a node from a cloned node it got me interested.  At first it seemed trivial but then I started getting frustrated with it.  The cloned node had a OwnerDocument so why was it not working.

Well the OwnerDocument is only half the story.  You need a ParentNode to successfully do a query on the cloned node.  The ParentNode is nulled when a clone is made.  Thus the answer is put the cloned node in another document.  So if  you want to clone a node and use it you will need to do something like below.

  private XmlNode Clone(XmlNode node, bool deep)
  {
      XmlNode clone = node.CloneNode(deep);
      XmlDocument cloneDoc = new XmlDocument();
      XmlNode importNode = cloneDoc.ImportNode(clone, true);
      cloneDoc.AppendChild(importNode);

      return importNode;
  }

Now Bob’s real issue is when he serializes/deserializes an element he can’t select a node (The clone issue seemed to mimic the same problem).  I suspect what I described above is what he is seeing.  The node is serialized and deserialized with no XmlDocument or ParentNode so you will always get null when querying for a node.

Friday, January 27, 2006 4:50:01 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview
All content © 2009, John Luif