Adding elements to xml file in C# using XDocument

5.4k views Asked by At

this is my current XML structure

<root>
<sublist>
    <sub a="test" b="test" c="test"></sub>
  </sublist>
</root>

i use the following C# but get error when i try to excute

 public static void writeSub(string a,string b,string c)
        {
            XDocument xDoc = XDocument.Load(sourceFile);
            XElement root = new XElement("sub");
            root.Add(new XAttribute("a", a), new XAttribute("b", b),
                         new XAttribute("c", c));
            xDoc.Element("sub").Add(root);
            xDoc.Save(sourceFile);
        }

where do i get it wrong?

error is

nullreferenceexception was unhandled
1

There are 1 answers

2
Sergey Berezovskiy On BEST ANSWER

You have problems because sub is not root element of document. So, when you do

xDoc.Element("sub").Add(root);

Then xDoc.Element("sub") returns null. Then when you try to call method Add you have NullReferenceException.

I think you need to add new sub element to sublist element:

xDoc.Root.Element("sublist").Add(root);

Also I suggest to improve naming. If you are creating element sub, then call varibale sub instead of naming it root (that is very confusing). E.g.

XDocument xdoc = XDocument.Load(sourceFile);
var sub = new XElement("sub", 
               new XAttribute("a", a), 
               new XAttribute("b", b),
               new XAttribute("c", c));

xdoc.Root.Element("sublist").Add(sub);
xdoc.Save(sourceFile);