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中使用以下内容。
<objects>
<ticket>
<object/>
</ticket>
</objects>
非常感谢任何帮助!
答案 0 :(得分:1)
您还需要多次调用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