سؤال

Goal:
To apply the XML data to the List _a

Problem:
When making transaction of Jessica black I retrieve the error message "{"Object reference not set to an instance of an object."}" at the source code "_ab.age = li.Element("age").Value;" because there is no data of Jessicas age in the xml. Same problem can be for Jim West's sex.

What should I do? I started getting crazy!

enter image description here


C # below

public class Program
{
private static List<user> _a = new List<user>();
private static user _ab = new user();


static void Main(string[] args)
{
    XDocument xml = XDocument.Load("xml file....");

    xml.Root.Descendants("user").ToList().ForEach(li =>
    {
        _ab = new user();
        _ab.firstname = li.Element("firstname").Value;
        _ab.lastname = li.Element("lastname").Value;
        _ab.age = li.Element("age").Value;
        _ab.sex = li.Element("sex").Value;
        _a.Add(_ab);
    }
}
}

public class user
{
    public String firstname;
    public String lastname;
    public String age;
    public String sex;
}   

XML code below

<users>
    <user>
        <firstname>sara</firstname>
        <lastname>brown</lastname>
        <age>20</age>
        <sex>female</sex>
    </user>
    <user>
        <firstname>Jessica</firstname>
        <lastname>black</lastname>
        <sex>Female</sex>
    </user>
    <user>
        <firstname>Jim</firstname>
        <lastname>west</lastname>
        <age>26</age>
    </user>
    <user>
        <firstname>robert</firstname>
        <lastname>lake</lastname>
        <age>41</age>
        <sex>male</sex>
    </user>
    <user>
        <firstname>Britany</firstname>
        <lastname>McLove</lastname>
        <age>21</age>
    </user>
</users>    
هل كانت مفيدة؟

المحلول

Use conversation operator:

_ab.age = (string)li.Element("age");

and so on...

If element age doesn't exist, (string)li.Element("age") will return null and won't throw any exception.

نصائح أخرى

Just test if the element is not null before getting it's Value :

    xml.Root.Descendants("user").ToList().ForEach(li =>
    {
        _ab = new user();
        if (li.Element("firstname") != null) _ab.firstname = li.Element("firstname").Value;
        if (li.Element("lastname") != null) _ab.lastname = li.Element("lastname").Value;
        if (li.Element("age") != null) _ab.age = li.Element("age").Value;
        if (li.Element("sex") != null) _ab.sex = li.Element("sex").Value;
        _a.Add(_ab);
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top