2015-06-19 126 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