Search code examples
c#xmlmethodsxml-parsingxmldocument

How do i Return null or matching xml node as Object in C#


I got a xml structure as below:

<Users>
<User Code="1" Roles="1,2,3" />
</Users>

I provide a method to search the xml file for retrieving particular user based on code like below

    string xpath = "Users/User[@Code="+ Code +"]";
    XmlNode user = _xmlDatabase.SelectSingleNode(xpath);
    if (user != null)
    {
        XmlAttributeCollection userMeta = user.Attributes;
        if (userMeta != null)
        {
            int code = int.Parse(Code);
            User userInstance = new User(Code, userMeta[1].Value, userMeta[2].Value);
            return userInstance;
        }
    }

i would invoke the method like so User user = GetUserByCode("1"); & _xmlDatabase is a instance of XmlDocument class. Here is the question,

  • I get to return null when no matching user is found
  • Attributes i search for does not exists
  • It's a fresh file

Hence i modified the method to return "null"only to be complained by compiler that "return statement is missing"

I kind of wanted the end-user to do

User user = GetUserByCode("1");
if(user == null)
  Display "No User Found"

Solution

  • please see the comments on below code

       if (user != null) // if user == null nothing will return 
        {
            XmlAttributeCollection userMeta = user.Attributes;
            if (userMeta != null) // if userMeta == null nothing will return 
            {
                int code = int.Parse(Code);
                User userInstance = new User(Code, userMeta[1].Value, userMeta[2].Value);
                return userInstance;
            }
        }
    

    you can solve this as below

    public User GetUserByCode(string Code)
    {
        User userInstance = null;
        string xpath = "Users/User[@Code="+ Code +"]";
        XmlNode user = _xmlDatabase.SelectSingleNode(xpath);
        if (user != null)
        {
            XmlAttributeCollection userMeta = user.Attributes;
            if (userMeta != null)
            {
                int code = int.Parse(Code);
                userInstance = new User(Code, userMeta[1].Value, userMeta[2].Value);
            }
        }
    
        return userInstance;
    }
    

    Above code will return null or userInstance in any case.