I have code that deserializes XMLDocument into an array. But it throws NullReferenceException any time I call it in Xamarin.Forms Android project. After days of debugging I created a .NET Console App, coppied the problematic code into it and lo and behold it works flawlessly. Can anyone help me with this problem ? Here is the XMLDocument i'm working with:
<?xml version="1.0" encoding="utf-8" ?>
<Otazky>
<Otazka>
<Typ>ABC</Typ>
<Bodu>1</Bodu>
<Ukol> Ve kterém z následujících souvětí není chyba v interpunkci?</Ukol>
<Moznosti>
<Moznost>A) Po vyčerpávajících mrazech</Moznost>
<Moznost>B) Mé obavy se každým dnem stupňovaly,</Moznost>
<Moznost>C) Pokud snížím množství sladkostí</Moznost>
<Moznost>D) Rodiče celý víkend usilovně přemýšleli</Moznost>
</Moznosti>
<Spravna>C</Spravna>
</Otazka>
<Otazka>
<Typ>Vyber</Typ>
<Bodu>2</Bodu>
<Ukol> Ukol2 </Ukol>
<Moznosti>
<Moznost>A) Po vyčerpávajících mrazech</Moznost>
<Moznost>B) Mé obavy se každým dnem stupňovaly</Moznost>
<Moznost>C) Pokud snížím množství sladkostí</Moznost>
<Moznost>D) Rodiče celý víkend usilovně přemýšleli</Moznost>
</Moznosti>
<Spravna>D</Spravna>
</Otazka>
</Otazky>
Here are the classes I use to store each Otazka element:
public class Otazka
{
[XmlElement(ElementName = "Typ")]
public string Typ { get; set; }
[XmlElement(ElementName = "Bodu")]
public int Bodu { get; set; }
[XmlElement(ElementName = "Ukol")]
public string Ukol { get; set; }
[XmlElement(ElementName = "Moznosti")]
public Moznosti Moznosti { get; set; }
[XmlElement(ElementName = "Spravna")]
public string Spravna { get; set; }
}
[XmlRoot(ElementName = "Otazky")]
public class Otazky
{
[XmlElement(ElementName = "Otazka")]
public List<Otazka> Otazka { get; set; }
}
And finally the code that deserializes the XML into my class:
Otazka[] LoadXMLData()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DDKTCKE_APP.MyResources.Otazky.xml"))
{
XDocument doc = XDocument.Load(stream);
var result = from q in doc.Descendants("Otazka")
select new Otazka
{
Typ = q.Element("Typ").Value,
Bodu = Convert.ToInt32(q.Element("Bodu").Value),
Ukol = q.Element("Ukol").Value,
Moznosti = new Moznosti(q.Element("Moznosti").Elements().Select(x => x.Value).ToList()),
Spravna = q.Element("Spravna").Value
};
return result.ToArray();
}
}
The NullReferenceException is thrown in the line that returns results.ToArray(). Also when i enclosed the whole function in a Try...Catch block it didn't catch anything.