将信息添加到现有xml

时间:2015-08-19 08:59:00

标签: c# xml linq

要将信息添加到激动的xml文件,我有以下代码:

我在行" IEnumerable rows = root.Descendants(" History");"在else语句中。见评论..

  

对象引用未设置为对象的实例。

private static void CreateXMLFile(string text, string time)
    {
        lastID++;

        if (!(File.Exists(path + @"\CM.xml")))
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            //Create first node
            XmlNode ClipboardHistoryNode = doc.CreateElement("ClipBoardHistory");
            doc.AppendChild(ClipboardHistoryNode);

            //Create second node
            XmlNode HistoryNode = doc.CreateElement("History");
            XmlAttribute idAttribute = doc.CreateAttribute("ID");
            idAttribute.Value = lastID.ToString();
            XmlAttribute textAttribute = doc.CreateAttribute("Text");
            textAttribute.Value = text;
            XmlAttribute timeAttribute = doc.CreateAttribute("Time");
            timeAttribute.Value = time;
            HistoryNode.Attributes.Append(idAttribute);
            HistoryNode.Attributes.Append(textAttribute);
            HistoryNode.Attributes.Append(timeAttribute);

            ClipboardHistoryNode.AppendChild(HistoryNode);

            //Save file at the executing location

            doc.Save(path + @"\CM.xml");
        }
        else
        {
               XDocument xDocument = XDocument.Load(path + @"\CM.xml");
               XElement root= xDocument.Element("History");
               IEnumerable<XElement> rows = root.Descendants("History"); //Object reference not set to an instance of an object.
               XElement firstRow= rows.First();
               firstRow.AddBeforeSelf(
               new XElement("ID", lastID,
               new XElement("Text", text,
               new XElement("Time", time))));
               xDocument.Save(path + @"\CM.xml");
        }
    }

使用此(请参阅接受的答案):Stackoverflow question

此代码有什么问题?

修改

当前XML

<?xml version="1.0" encoding="UTF-8"?>
<ClipBoardHistory>
    <History ID="15" Text="ClipboardManager.vshost.exe" Time="10:05" />
</ClipBoardHistory>

0 个答案:

没有答案