Answered Copy xml element between documents

  • Sunday, August 14, 2011 12:45 PM
     
     

    Hello ,

    I am trying to copy a xml element from one document to another but

    I am facing to following exception :

    "The node to be inserted is from a different document context"

    This is my function:

       private void CopyElement(XmlDocument source,XmlDocument target,string elemId)
            {
                XmlNode nodeToCopy     =   source.ImportNode(source.GetElementById(elemId),true);
                XmlNode parentNode      =   target.GetElementById(nodeToCopy.Attributes["appendTo"].Value);
                parentNode.AppendChild(nodeToCopy);
            } 

    Any help will be appreciated .

    Kind regards,

    Tal Humy

     

All Replies

  • Sunday, August 14, 2011 12:58 PM
     
     Answered
    you should do the import to the target. Something along the line:
     

       private void CopyElement(XmlDocument source,XmlDocument target,string elemId)
            {
                XmlNode nodeToCopy     =   target.ImportNode(source.GetElementById(elemId),true); // note: target
                XmlNode parentNode      =   target.GetElementById(nodeToCopy.Attributes["appendTo"].Value);
                parentNode.AppendChild(nodeToCopy);
            } 

    Hello ,

    I am trying to copy a xml element from one document to another but

    I am facing to following exception :

    "The node to be inserted is from a different document context"

    This is my function:

       private void CopyElement(XmlDocument source,XmlDocument target,string elemId)
            {
                XmlNode nodeToCopy     =   source.ImportNode(source.GetElementById(elemId),true);
                XmlNode parentNode      =   target.GetElementById(nodeToCopy.Attributes["appendTo"].Value);
                parentNode.AppendChild(nodeToCopy);
            } 

    Any help will be appreciated .

    Kind regards,

    Tal Humy

     


    /LM
    • Marked As Answer by Tal humy Sunday, August 14, 2011 1:09 PM
    •  
  • Sunday, August 14, 2011 1:03 PM
     
     Answered Has Code

    It's the target document that should import nodes. Your are actually importing node into the source document and the source document is the owner of nodeToCopy node.

     

    To fix your problem, replace

    XmlNode nodeToCopy   =  source.ImportNode(source.GetElementById(elemId),true);
     
    

    by

    XmlNode nodeToCopy   =  target.ImportNode(source.GetElementById(elemId),true);
     
    

    • Marked As Answer by Tal humy Sunday, August 14, 2011 1:09 PM
    •  
  • Sunday, August 14, 2011 1:08 PM
     
     
  • Sunday, August 14, 2011 1:09 PM
     
     

    Stupid mistake ,

    I didn't notice that.

    Thank you very much.