0

Here's the problem I have a xml file that I am trying to append data to. I am using LINQ to XML and the code I am using is as 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));

        <!------- The following line throws an 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 that I am opening is

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

I just don't see why I am getting a null reference exception.

5
  • Which object/which part is invoking the exception? Jan 10, 2012 at 15:50
  • @JamieKeeling The line under <!-- the following line throws an exception every time ---> :)
    – CBRRacer
    Jan 10, 2012 at 15:51
  • Assuming your file name is "Test" then does the xml have an element called "Test" in it? If you are trying to add an XElement to the xml then i guess you need to do something like thisDoc.Add(new XElement("Sale"));
    – Rajesh
    Jan 10, 2012 at 15:54
  • try this with element value -- thisDoc.Element(FileName).Add(new XElement("Sale","SaleValue"));
    – swapneel
    Jan 10, 2012 at 15:57
  • @swapneel tried that I actually have data from the Company object that I was passing in to the element but when it started throwing the exception and I paired it down to the above line so that I could test to see if I could just append a node to the xml file.
    – CBRRacer
    Jan 10, 2012 at 15:59

1 Answer 1

0

Element refers to direct child (which in your case would be root, not TestSale). Try Descendants instead:

thisDoc.Descendants(FileName).First().Add(new XElement("Sale"));

Alternatively, when you know XML tree you can also simply walk it like this:

thisDoc.Element("root").Element(FileName).Add(new XElement("Sale"));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.