1. 程式人生 > >不同XML之間節點的拷貝

不同XML之間節點的拷貝

Soon after I recommended my (just published solution) for merging XML files for a person I know he contacted me and said he was getting the error "The node to be inserted is from a different document context ".

After some investigating it turned out he had not copied the solution by using the clipboad function, but rather typing it in - and missed the oh so important oDocFirst.ImportNode 

call.

I.e he was using code like:

XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode("/rss/channel"); 
foreach( XmlNode oNode in oDocSecond.SelectNodes("/rss/channel/item")) 
{ 
    oNodeWhereInsert.AppendChild(oNode.Clone()); 
} 
 

instead of
 
XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode("/rss/channel"); 
foreach( XmlNode oNode in oDocSecond.SelectNodes("/rss/channel/item")) 
{ 
    oNodeWhereInsert.AppendChild(oDocFirst.ImportNode(oNode,true)); 
} 
PunCha注: 在被拷貝的節點來自於其他XmlDocument是,可以使用XmlDocument.ImportNode來匯入節點。