-5

Following code throws a

System.NullReferenceException

 private void btnLoad_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Title = "XML-Datei auswählen";
        ofd.Filter = "XML-Dateien|*.xml";
        ofd.InitialDirectory = @"C:\";

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(ofd.FileName);

            foreach (XmlNode node in xDoc.SelectNodes("People/Person"))
            {
                int age = int.Parse(node.Attributes["Age"].Value);
                MessageBox.Show((age + 1).ToString());
            }
        }

    }

The error occurs in the line

age = int.Parse(node.Attributes["Age"].Value);

In the locals window I can see, that the reference for the attribut "Age" remains null.

The .xml-file is structured like that:

<People>
 <Person>
  <Name>TestPeron</Name>
  <Age>29</Age>
  <Email>me@testmail.com</Email>
  </Person>
</People>

Thank you!

Dhanuka
  • 2,704
  • 5
  • 25
  • 37

4 Answers4

0

There is no attribute by that name, only an element.

Ted Nyberg
  • 5,861
  • 7
  • 35
  • 62
0
int age = int.Parse(node["Age"].InnerText)
va.
  • 818
  • 3
  • 15
  • 37
0

Try this

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string input =
                "<People>" +
                    "<Person>" +
                        "<Name>TestPeron</Name>" +
                        "<Age>29</Age>" +
                        "<Email>me@testmail.com</Email>" +
                    "</Person>" +
                "</People>";

            XDocument doc = XDocument.Parse(input);
            foreach(XElement person in doc.Descendants("Person"))
            {
                string message = string.Format("Name : {0}, Age : {1}, Email : {2}",
                    person.Element("Name").Value,
                    person.Element("Age").Value,
                    person.Element("Name").Value);

                MessageBox.Show(message);
                Console.ReadLine();
            }

        }
    }
}
​
jdweng
  • 28,546
  • 2
  • 13
  • 18
0

You are attempting to deference an object which is basically a null object. So use try and catch to handle null-reference exception and see if the issue resolves

Phanindra
  • 51
  • 2
  • 10