You probably don't want to mix
XmlDocument
and
XDocument
. You end up loading the same file twice, which could become a problem if your file grows sufficiently large.
There's also no real point in counting the
Sub
elements, since
SingleOrDefault
will throw an exception if there is more than one. Did you want to count the child elements of the
Sub
element instead?
XDocument doc = XDocument.Load("Klassen/NeueKlasse1.xml");
if (doc.Root == null)
{
doc.Add(new XElement("NewDataSet"));
}
XElement subNode = doc.Root.Element("Sub");
if (subNode == null)
{
subNode = new XElement("Sub");
doc.Root.Add(subNode);
}
int neuSchV = subNode.Elements().Count();
XElement subAddNode = new XElement("SubAdd" + neuSchV);
subNode.Add(subAddNode);
doc.Save("Klassen/NeueKlasse1.xml");