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
You have problems because
sub
is not root element of document. So, when you doThen
xDoc.Element("sub")
returnsnull
. Then when you try to call methodAdd
you haveNullReferenceException
.I think you need to add new
sub
element tosublist
element:Also I suggest to improve naming. If you are creating element
sub
, then call varibalesub
instead of naming itroot
(that is very confusing). E.g.