Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to count out the elements within a root, then add an element to that root and give it a name based on the count from the beginning. Here is my XML:

HTML
<NewDataSet>
  <Klasse>
   
  </Klasse>
  <Sub>

  </Sub>
</NewDataSet>


and here is my code:

C#
private void buttonSchSave_Click(object sender, EventArgs e)
 {

     XmlDocument xmldoc = new XmlDocument();
     xmldoc.Load("Klassen/NeueKlasse1.xml");
     int neuSchV = xmldoc.SelectNodes("Sub").Count;

     XDocument doc = XDocument.Load("Klassen/NeueKlasse1.xml");

     XElement root = new XElement("SubAdd" + neuSchV);
     var elementName = doc.Descendants("Sub")?.SingleOrDefault();
     elementName.Add(root);



     doc.Save("Klassen/NeueKlasse1.xml");





 }


The Problem is: all the elements "SubAdd" are named: SubAdd0

The Xml Element Count always seems to return the value 0, any ideas on how to solve this?

Thanks.

What I have tried:

searching for a similar problem, didn't really find anything i could use.
Posted
Updated 12-Sep-17 10:21am

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");
 
Share this answer
 
int neuSchV = xmldoc.SelectNodes("/NewDataSet/Sub").Count;

refer Select XML Nodes by Name [C#][^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900