0
namespace Project
{
    internal class Class1
    {
        public string[] UnpackXML(string xml_string)
        {
            string response = xml_string;
            string[] return_values = new string[6];

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(response);

            return_values[0] = xml.GetElementsByTagName("meas name=\"mt1\"")[0].InnerText.ToString();
            return_values[1] = xml.GetElementsByTagName("meas name=\"mt2\"")[0].InnerText.ToString();
            return_values[2] = xml.GetElementsByTagName("meas name=\"mt3\"")[0].InnerText.ToString();
            return_values[3] = xml.GetElementsByTagName("meas name=\"mt4\"")[0].InnerText.ToString();
            return_values[4] = xml.GetElementsByTagName("meas name=\"mt5\"")[0].InnerText.ToString();
            return_values[5] = xml.GetElementsByTagName("meas name=\"mt6\"")[0].InnerText.ToString();

            return return_values;

        }
    }
}

When running the above code, it fails with the given error code:

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

At the first line where I try to give return_values[0] a new value:

return_values[0] = xml.GetElementsByTagName("meas name=\"mt1\"")[0].InnerText.ToString();

The input to the UnpackXML is just an API response given as a XML-string. The XML document has the following format:

<response location='location1'>
    <meas name='mt1'>14</meas>
    <meas name='mt2'>23</meas>
    <meas name='mt3'>65</meas>
    <meas name='mt4'>31</meas>
    <meas name='mt6'>32</meas>
</response>

Any ideas how to fix this? I basically want to append specific fields from the XML-file to an array.

bullfighter
  • 397
  • 1
  • 4
  • 21
  • 1
    As an aside, I'd strongly recommend using LINQ to XML instead of the old XmlDocument API - it's a *much* simpler way of working with XML. You should think about the difference between an element name and its attributes though: `meas name="mt6"` is *not* an element name. – Jon Skeet Sep 30 '22 at 08:14

0 Answers0