Mona Coder Mona Coder - 8 months ago 24
C# Question

Having Issue on Reading XML File

Using C# I have an XML file like

<?xml version="1.0" encoding="utf-8"?>

and I also have a function to read the name node as:

XmlDocument xmlDoc = new XmlDocument();
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();

but I am getting index out of range error as:

enter image description here

Can you please let me know why this is happening?

node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;

node is your root node. Which looks like this:


How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:

<foo bar="baz">

node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.

What you want is an element named name, which is farther down inside your XML tree.

Probably this:

var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");

And then you'll want to look at node.InnerText to get "Jani" out of it.