关于XML,获取孩子,编辑孩子,保存孩子

时间:2011-04-05 06:58:20

标签: c# xml xmldocument

我目前正在做一个项目,需要我只保存10个子节点,一旦保存11,它将覆盖第一个。

这是我目前的代码

if (File.Exists("xmlData.xml") == false)
        {

            XmlDocument xmlData = new XmlDocument();
            // Create the root element
            XmlElement rootNode = xmlData.CreateElement("HistoryList");
            xmlData.AppendChild(rootNode);
            XmlNode RootNode = xmlData["HistoryList"];
            //XmlNodeList nodelist = xmlData.GetElementsByTagName("History");

            // Create a new <Category> element and add it to the root node
            XmlNode parentNode = xmlData.CreateElement("History");
            rootNode.AppendChild(parentNode);


            // Add a Date element.
            XmlElement newDate = xmlData.CreateElement("Date");
            newDate.InnerText = timeTextBox.Text;
            parentNode.AppendChild(newDate);

            // Add a distance element.
            XmlElement newDistance = xmlData.CreateElement("Distance");
            newDistance.InnerText = distanceTextbox.Text;
            parentNode.AppendChild(newDistance);
            // Add a distance element.
            XmlElement newTimeTaken = xmlData.CreateElement("TimeTaken");
            newTimeTaken.InnerText = timeTakenTextbox.Text;
            parentNode.AppendChild(newTimeTaken);
            i++;

            xmlData.Save("xmlData.xml");
        }
        else
        {


            XmlDocument xmlData = new XmlDocument();
            xmlData.Load("xmlData.xml");

            XmlNode RootNode = xmlData["HistoryList"];
            xmlData.AppendChild(RootNode);


            //get all nodes with history
            XmlNodeList nodelist = xmlData.GetElementsByTagName("History");            

            foreach (XmlNode Node in nodelist)
            {

            }

            XmlNode parentNode = xmlData.CreateElement("History");
            RootNode.AppendChild(parentNode);

            // Add a Date element.
            XmlElement newDate = xmlData.CreateElement("Date");
            newDate.InnerText = timeTextBox.Text;
            parentNode.AppendChild(newDate);

            // Add a distance element.
            XmlElement newDistance = xmlData.CreateElement("Distance");
            newDistance.InnerText = distanceTextbox.Text;
            parentNode.AppendChild(newDistance);

            // Add a distance element.
            XmlElement newTimeTaken = xmlData.CreateElement("TimeTaken");
            newTimeTaken.InnerText = timeTakenTextbox.Text;
            parentNode.AppendChild(newTimeTaken);

            xmlData.Save("xmlData.xml");

    }
}

0 个答案:

没有答案