Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
so im tring to to loop trough some nodes in xml.

my xml file looks like this :
XML
<?xml version="1.0" encoding="utf-8" ?>
<RoundType>
  
  <name>
   StartRound
  </name>
  
  <ActionGroups>
    
    <group>
      <name>
        STANDART
      </name>
      <path>
        STANDART
      </path>
    </group>
    
  </ActionGroups>
  
</RoundType>

i have tried this:
C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace SurvivalGamesLib
{
    class ActionHandler
    {
        public List<XmlDocument> LoadActions(XDocument roundType) 
        {
            List<XmlDocument> actions = new List<XmlDocument>();

            List<string> groups = new List<string>();

            

            foreach (var node in roundType.Element("RoundType").Element("ActionGroups").Elements("group"))
            {
                Console.WriteLine("test");
                Console.WriteLine(node.Element("name").Value);
            }


            return actions;
        }

    }
}


but when i run it i always get this error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Xml.Linq.XContainer.Element(...) returned null.


is there someone that knows a solution for this ?

What I have tried:

searching google. but al the solutions i found did not work in my case.
Posted
Updated 27-Mar-19 4:31am

1 solution

Try this:

C#
foreach (var node in roundType.Root.Descendants("group"))
{
    groups.Add(node.Element("name").Value);
}


or:
C#
List<string> groups = roundType.Root
    .Descendants("group")
    .Select(node => node.Element("name").Value)
    .ToList();
 
Share this answer
 
v2

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