2015-06-19 162 views
0

我必須聲明,如果我需要修改,以便它檢查是否規約ID是一個數字(123654)等如何檢查ID是否是數字?

如果規約ID不是數字的錯誤消息應該說「規約ID值不是一個數字「

vb.net代碼

'Check to see if we got statuteId and make sure the Id string length is > than 0 
     If Not objXmlGetStatuteRequestNode.SelectSingleNode("ss:Statute/ss:StatuteId/ss:Id[string-length(.)>0]", objXMLNameSpaceManager) Is Nothing Then 

示例XML文檔

<?xml version="1.0" encoding="UTF-8"?> 
<GetStatuteRequest> 
    <Statute> 
     <StatuteId> 
      <ID>15499</ID> 
     </StatuteId> 
    </Statute> 
</GetStatuteRequest> 
+0

谷歌Int.TryParse – Cortright

回答

0

正如我可以從你的問題和史蒂夫的回答看,你需要/想是這樣的......

Dim node As XmlNode = objXmlGetStatuteRequestNode.SelectSingleNode("ss:Statute/ss:StatuteId/ss:Id[string-length(.)>0]", objXMLNameSpaceManager) 
If node IsNot Nothing Then 
    If IsNumeric(node.InnerText) Then 
     //...Do Stuff 
    Else 
     Throw New Exception("Statute ID Value is not a number") 
    End If 
Else 
    //... Do Something Else 
End If 
+0

謝謝Josh Part – Angela

2

在數字中轉換字符串的正確方法是通過Int32.TryParse方法。這個方法檢查你的字符串是否是一個有效的整數,如果不是,則返回false而不拋出任何性能代價高昂的異常。

所以,你的代碼可以簡單地這樣寫的

Dim doc = new XmlDocument() 
doc.Load("D:\TEMP\DATA.XML") 


Dim statuteID = doc.GetElementsByTagName("ID") 
Dim id = statuteID.Item(0).InnerXml 

Dim result As Integer 
if Not Int32.TryParse(id, result) Then 
    Console.WriteLine("Statute ID Value is not a number") 
Else 
    Console.WriteLine(result.ToString()) 
End If 

當然了很多檢查都需要圍繞XML文件的加載和分析,以加入,但是這不是你的問題

的說法
+0

史蒂夫感謝您的幫助。我唯一的問題是,我的老闆希望我以這種方式如何處理If語句。然後用我之前發佈的消息拋出異常。你的方式似乎更好,但他們不會讓我這樣做! – Angela

+0

目前尚不清楚。您的代碼嘗試評估字符串長度,而不是字符串是數字。你在找什麼? – Steve

1

您也可以使用IsNumeric功能:

Private Function IsIdNumeric(ByVal strXmlDocumentFileNameAndPath As String) As Boolean 

    Return ((From xmlTarget As XElement 
      In XDocument.Load(New System.IO.StreamReader(strXmlDocumentFileNameAndPath)).Elements("GetStatuteRequest").Elements("Statute").Elements("StatuteId").Elements("ID") 
      Where IsNumeric(xmlTarget.Value)).Count > 0) 

End Function 

然後調用它像這樣:

If Not IsIdNumeric("C:\Some\File\Path.xml") Then 

     Throw New Exception("Statute ID Value is not a number") 

    End If