开发者

How to add child node to the root element in an XML file using C#

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


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());


try this:

            XmlElement cpyXEle = XEle.Clone() as XmlElement;
            TestChild.AppendChild(XEle);
            RootNode.AppendChild(cpyXELe);


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜