c# - LINQ to XML Append Data throws null reference exception -



c# - LINQ to XML Append Data throws null reference exception -

here's problem have xml file trying append info to. using linq xml , code using follows:

public void appendsalesxmldata(company company) { string filename = "testsales"; string orgid = company.orgid.tostring(); string saleid = company.orgsales[company.orgsales.count - 1].saleid.tostring(); if (!file.exists(string.format(@"c:\data-source\trunk\applications\vintagesiteinspector\xml\{0}.xml", filename))) { createxmlfile(filename); } xdocument thisdoc = xdocument.load(string.format(@"c:\data-source\trunk\applications\vintagesiteinspector\xml\{0}.xml", filename)); <!------- next line throws exception every time. -----> thisdoc.element(filename).add(new xelement("sale")); thisdoc.save(string.format(@"c:\data-source\trunk\applications\vintagesiteinspector\xml\{0}.xml", filename)); }

the xml file opening

<?xml version="1.0" encoding="utf-8"?> <root> <testsales></testsales> </root>

i don't see why getting null reference exception.

element refers direct kid (which in case root, not testsale). seek descendants instead:

thisdoc.descendants(filename).first().add(new xelement("sale"));

alternatively, when know xml tree can walk this:

thisdoc.element("root").element(filename).add(new xelement("sale"));

c# xml winforms linq linq-to-xml

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -