Как я возвращаю нулевой или соответствующий узел XML как объект в C # - PullRequest
0 голосов
/ 04 ноября 2011

Я получил структуру XML, как показано ниже:

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

Я предоставляю метод поиска в файле XML для получения конкретного пользователя на основе кода, подобного приведенному ниже

    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;
        }
    }

Я бы вызвалтакой метод User user = GetUserByCode("1"); & _xmlDatabase является экземпляром класса XmlDocument.Вот вопрос,

  • Я могу вернуть ноль, когда не найдено ни одного подходящего пользователя
  • Атрибутов, которые я ищу, не существует
  • Это свежий файл

Поэтому я изменил метод так, чтобы он возвращал "null" только для того, чтобы компилятор жаловался, что "return statement is missing"

Я как бы хотел, чтобы конечный пользователь сделал

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

1 Ответ

1 голос
/ 04 ноября 2011

см. Комментарии к приведенному ниже коду

   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;
        }
    }

. Вы можете решить эту проблему, как показано ниже

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;
}

Приведенный выше код вернет значение null или userInstance в любом случае.

...