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