Creating xmlDocument from another document

I am trying to create an xmldocument object using another XML

see code below:

 objNewsDoc.LoadXml(strNewsDetail); // Current XML XmlDocument docRss = new XmlDocument(); // new Xml Object i Want to create XmlElement news = docRss.CreateElement("news"); // creating the wrapper news node news.AppendChild(objNewsDoc.SelectSingleNode("newsItem")); // adding the news item from old doc 

Error: The inserted node refers to a different document context

Edit 1 Complete the code block:

 try { XmlDocument objNewsDoc = new XmlDocument(); string strNewsXml = getNewsXml(); objNewsDoc.LoadXml(strNewsXml); var nodeNewsList = objNewsDoc.SelectNodes("news/newsListItem"); XmlElement news = docRss.CreateElement("news"); foreach (XmlNode objNewsNode in nodeNewsList) { string newshref = objNewsNode.Attributes["href"].Value; string strNewsDetail = getNewsDetailXml(newshref); try { objNewsDoc.LoadXml(strNewsDetail); XmlNode importNewsItem = docRss.ImportNode(objNewsDoc.SelectSingleNode("newsItem"), true); news.AppendChild(importNewsItem); } catch (Exception ex) { Console.Write(ex.Message); } } docRss.Save(Response.Output); } catch (Exception ex) { Console.Write(ex.Message); } 
+7
source share
1 answer

You need to use the Import Node method to import the XmlNode from the first document into the context of the second:

 objNewsDoc.LoadXml(strNewsDetail); // Current XML XmlDocument docRss = new XmlDocument(); // new Xml Object i Want to create XmlElement news = docRss.CreateElement("news"); // creating the wrapper news node //Import the node into the context of the new document. NB the second argument = true imports all children of the node, too XmlNode importNewsItem = docRss.ImportNode(objNewsDoc.SelectSingleNode("newsItem"), true); news.AppendChild(importNewsItem); 

EDIT

You are very close to your answer, the main problem that you are facing right now is that you need to add your news item to your main document. I would recommend doing the following if you want your output to look like this:

 <news> <newsItem>...</newsItem> <newsItem>...</newsItem> </news> 

Instead of creating a new XmlElement, news, instead, when creating docRSS, follow these steps:

 XmlDocument docRss = new XmlDocument(); docRss.LoadXml("<news/>"); 

Now you have an XmlDocument that looks like this:

 <news/> 

Then, instead of news.AppendChild simply:

 docRSS.DocumentElement.AppendChild(importNewsItem); 

This adds each newsItem under the news element (which in this case is a document element).

+10
source

All Articles