2011-11-04 40 views
0

我有如下一個XML結構:我如何返回null或匹配的XML節點對象在C#

<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沒有任何匹配的用戶發現
  • 屬性我尋找不存在
  • 這是一個新的文件

因此我修改的方法返回"null"只能由編譯器投訴"return statement is missing"

我有點想最終用戶做

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

如果你顯示你的整個方法,而不是隻包含一個不包含方法簽名或'return null'行的代碼片段,那麼可能會有所幫助。 –

+0

@KirkBroadhurst謝謝,但我已經接受了一個答案。在那裏的代碼是我必須爲你提供的。 – Deeptechtons

回答

1

請參閱下面代碼中的註釋

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在任何情況下。

+0

這很簡單,當我們進入主題時,簡單的事情就會被忽視。謝謝 – Deeptechtons