1

I'm trying to add dynamically elements to a root using LINQ, it was working before. But it returns "Object reference not set to an instance of an object.". It only works creating the new XElement instance manually.

try  
{
   XDocument xdoc = XDocument.Load(_documentName);
   XElement _newElements = new XElement(_rowName);

   foreach(string s in _commaSeparatedNameValues)
   {
       _newElements.Add(new XElement( s.Split(',')[0], s.Split(',')[1]));
   }

   xdoc.Element(_rowName).Add(_newElements);
   xdoc.Save(_documentName);
}
catch(Exception ex)
{
   string s = ex.Message;
}
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140

1 Answers1

1
XDocument xdoc = XDocument.Load(_documentName);       
XElement _newElements = new XElement(_rowName);
...
xdoc.Element(_rowName).Add(_newElements);

You never add _newElements to xdoc, so xdoc.Element(_rowName) will be null.
And otherwiser it would have been an attempt to add an element to itself.

The fix, untested:

//xdoc.Element(_rowName).Add(_newElements);
xdoc.Add(_newElements);

or more probably:

xdoc.Root.Add(_newElements);
H H
  • 263,252
  • 30
  • 330
  • 514