我有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>
答案 0 :(得分: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文件时需要添加很多检查,但这不是你问题的论据
答案 1 :(得分: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
答案 2 :(得分: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