我有一个if语句,我需要修改它来检查规约ID是否是一个数字(123654)等等。
如果法规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>发布于 2015-06-19 23:20:38
我从你的问题和史蒂夫的回答中可以看出,你需要/想要这样的东西.
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发布于 2015-06-19 21:18:34
在数字中转换字符串的正确方法是通过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文件的加载和解析过程中需要添加大量的检查,但这不是您问题的论点。
发布于 2015-06-19 21:26:41
您还可以使用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 Ifhttps://stackoverflow.com/questions/30947118
复制相似问题