tags:

views:

29

answers:

3

The xml file is having the following structure

<RootElement>
</RootElement>

i need to append the "Child" element to both RootElement and TestChild . For this I'm using the following code.

         List<string> Str = new List<string> {"a","b"};
        XmlDocument XDOC = new XmlDocument();
        XDOC.Load(Application.StartupPath + "\\Sample.xml");
        XmlNode RootNode = XDOC.SelectSingleNode("//RootElement");
        XmlNode TestChild = XDOC.CreateNode(XmlNodeType.Element, "TestChild", null);
        for (int Index = 0; Index < Str.Count; Index++)
        {
            XmlElement XEle = XDOC.CreateElement("Child");
            XEle.SetAttribute("Name", Str[Index]);
            TestChild.AppendChild(XEle);
            RootNode.AppendChild(XEle);
        }
        RootNode.AppendChild(TestChild);
        XDOC.Save(Application.StartupPath + "\\Sample.xml");

But with this i can append the child node to only the RootElement

The result should come like

    <RootElement>
    <Child Name="a"/>
    <Child Name="b"/>
    <TestChild>
        <Child Name="a"/>
        <Child Name="b"/>
    </TestChild>
</RootElement>

But now i'm getting like

    <RootElement>  
        <Child Name="a" />
        <Child Name="b" />
        <TestChild>
        </TestChild>
     </RootElement>

please give me a solution to do this

Thanks in advance

+1  A: 

try this:

            XmlElement cpyXEle = XEle.Clone() as XmlElement;
            TestChild.AppendChild(XEle);
            RootNode.AppendChild(cpyXELe);
Iale
+1  A: 

I think problem is coming because you are using same node element in both root and test so create clone and than add it

XmlElement XEle = XDOC.CreateElement("Child");
XEle.SetAttribute("Name", Str[Index]);
TestChild.AppendChild(XEle);
RootNode.AppendChild(XEle.Clone());
Pranay Rana
A: 

It is as others said that you need to clone the node. The reason for this in case it is not clear is that the node can only appear in one place in your dom tree. Originally you were putting it on the child and then in the following line when you put it on the root it moved it from the child to the root. It makes sense if you think about what that node would tell you when you asked it what its current parent was - it could only give one answer...

Chris