C# – XMLNodeType – C#

c++xml

Could someone explain in layman terms what this actually does?

XmlTextReader textReader = new XmlTextReader(workingDir + @"\ModulesList.xml");

            textReader.Read();

                if (textReader.Name == "Name")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;
                }
                if (nType == XmlNodeType.Text)
                {
                    listBox1.Items.Add(textReader.Value.ToString());
                }

I don't understand the purpose of XmlNodeType and NodeType on the textreader. Please could someone clear it up for it in like the simplest way 😛

Best Solution

An XmlReader is like a forward-only cursor through an XML document. Aside from the fact that your code won't compile (you're declaring nType in one block and then using it in another), XmlReader.NodeType returns the current type of node the XML reader is looking at - an element, a text node, an attribute etc. XmlNodeType is the enum of possible values for XmlReader.NodeType.

Each time you call Read, the reader will move on to the next node - and what you want to do with that node will often depend on its type.

Personally I would steer clear of XmlReader unless you're trying to read a huge document which won't fit into memory. It's a much harder API to use properly than APIs which load a whole document into a tree, and let you navigate around that tree. LINQ to XML is a particularly nice API if you're in a situation where you can use it.