如何使用 C# 和 XmlDocument 多次 AppendChild?

How to AppendChild multiple times using C# and XmlDocument?

AppendChild 使用 C# 将节点添加到 XML 文件并遇到了困难。我似乎无法添加多个节点。

    private void saveBtn_Click(object sender, EventArgs e)
{
    int listCount = listView1.Items.Count;



    XmlDocument xmlDocNew = new XmlDocument();
    xmlDocNew.Load(@"D:\test.xml");
    XmlNodeList ticketNodes = xmlDocNew.SelectNodes(@"//objects/ticket");
    int ticketCount = ticketNodes.Count;
    XmlElement mapElement = (XmlElement)xmlDocNew.SelectSingleNode(@"//objects[last()]");

    var newRec = xmlDocNew.CreateElement("ticket");
    newRec.SetAttribute("number", conBox.Text);
    mapElement.AppendChild(newRec);

    XmlNode node = xmlDocNew.SelectSingleNode(@"//objects/ticket[@number='" + conBox.Text + "']");


    XmlElement objectRec = xmlDocNew.CreateElement("object");
    newRec.AppendChild(objectRec);

    xmlDocNew.Save(@"D:/test.xml");

}

即使我使用 newRec.AppendChild(objectRec) 两次,或者如果我将它包含在 for 或 foreach 循环中,我最终只会在 Xml.[=12= 中得到以下内容]

<objects>
    <ticket>
        <object/>
    </ticket>
</objects>

非常感谢任何帮助!

您还需要多次调用CreateElement:

for (int i = 0; i < 10; i++)
{
    XmlElement objectRec = xmlDocNew.CreateElement("object");
    objectRec.InnerText = i.ToString();
    newRec.AppendChild(objectRec);
}

当您重复使用相同的元素时,它被视为移动。参见:https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild(v=vs.110).aspx