Logo 
Search:

C# Answers

Ask Question   UnAnswered
Home » Forum » C#       RSS Feeds
  Question Asked By: Armando Peterson   on Sep 28 In C# Category.

  
Question Answered By: Roosevelt Jenkins   on Sep 28

The node  to be inserted  is from a different document  context.
Error generally occur when you copy  xml from different documents.

Cause for error:
Possible reason can be you are using AppendChild() incorrectly.

Solutions:
First import node using ImportNode method and then append it using AppendChild().

Following example imports node from xml  document into another xml document.
XmlDocument.ImportNode Method

The following example imports a node from a second XML document into the original XML
document.

VB.Net Example
Option Explicit
Option Strict
Imports System
Imports System.IO
Imports System.Xml
Public Class Sample

Public Shared Sub Main()
'Create the XmlDocument.
Dim xdoc As New XmlDocument()

'Loading xml from string
xdoc.LoadXml("<employee><emp
category='Manager'><name>Steve</name></emp></employee>")

'Create another XmlDocument and loading xml from file
Dim xdocEmp As New XmlDocument()
xdocEmp.Load("emp.xml")

'Import the last node
Dim newEmp As XmlNode = xdoc.ImportNode(xdocEmp.DocumentElement.LastChild, True)

' Appending Child
xdoc.DocumentElement.AppendChild(newEmp)

xdoc.Save(Console.Out)
End Sub
End Class


C# Example

using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
//Create the XmlDocument.
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml("<employee><emp category='Manager'><name>Steve</name></emp></employee>");

//Create another XmlDocument and loading xml from file
XmlDocument xdocEmp = new XmlDocument();
xdocEmp.Load("emp.xml");
//Import the last node
XmlNode newEmp = xdoc.ImportNode(xdocEmp.DocumentElement.LastChild, true);

//Appending Child
xdoc.DocumentElement.AppendChild(newEmp);

xdoc.Save(Console.Out);
}
}

Version: ASP.net 1.x

Share: 

 
 


Tagged: