To add information to a excisting xml file I have this code:
I have a problem at row "IEnumerable rows = root.Descendants("History");" in the else statement. See comment..
Object reference not set to an instance of an object.
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");
}
}
Used this(see accepted answer): Stackoverflow question
What is wrong in this code?
EDIT
Current XML
<?xml version="1.0" encoding="UTF-8"?>
<ClipBoardHistory>
<History ID="15" Text="ClipboardManager.vshost.exe" Time="10:05" />
</ClipBoardHistory>