append cloned node to same xml document



Am trying to append a clone node lets say



<Property Id="3" Name="Deadline"></Property>


into the same document with class name "AlphaCertificationsIndividual" but the compiler gives me this error: The node to be inserted is from a different document context



<Root>
<Class Name="ECMInstruction" Style="Top">
<Entity Id="1" Name="DocumentInformation" />
<Entity Id="2" Name="CustomerInformation" />
<Property Id="1" Name="DocumentTitle">
</Property>
<Property Id="2" Name="DateCreated">
<Lists>
<ListName>ws_Users</ListName>
<ListName>dfdfdfd</ListName>
</Lists>
</Property>
<Property Id="3" Name="Deadline">
</Property>
</Class>
<Class Name="AlphaCertificationsIndividual" Style="Top">
<Entity Id="1" Name="DocumentInformation" />
<Property Id="1" Name="DocumentTitle">
</Property>
<Property Id="2" Name="DateCreated">
<Lists>
<ListName>ws_Users</ListName>
<ListName>dfdfdfd</ListName>
</Lists>
</Property>
<Property Id="3" Name="Deadline">
</Property>
</Class>
</Root>


the code am using:



XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("sample.xml");
foreach (string id in properties)
{
XmlNode props = xmldoc.DocumentElement.SelectSingleNode("//Class[@Name='" + curClass + "']/Property[@Id='" + id + "']");

XmlNode cloneNode = props.CloneNode(true);

foreach (var item in dcList.SelectedItems)
{
XmlNodeList classes = commonMethods.LoadDocument(xml).DocumentElement.SelectNodes("//Class[@Name='" + item + "']/Property[last()]");
foreach (XmlNode c in classes)
{
String propertyid = c.Attributes["Id"].Value.ToString();
int.TryParse(propertyid, out value);
value = value + 1;
cloneNode.Attributes["Id"].Value = value.ToString();
c.ParentNode.AppendChild(xmldoc.ImportNode(cloneNode,true));
xmldoc.Save("sample.xml");
}
}
}

No comments:

Post a Comment