Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get CompletedDate from XML document element name CompDate. This is an optional element. When the XML document has a CompDate element my VB.NET code works. However when the XML document does not have CompDate element, I get Object reference not set to an instance of an object?

How do I fix this so it works whether or not the CompDate element exist in the XML Document?

XML Document

XML
<Integration>
   <Case>
     <CaseEvent ID="252949395">
	<CompDate>06/01/2019</CompDate>
     </CaseEvent>
   </Case>
   <IntegrationConditions>
      <IntegrationCondition>
	 <NotificationEvent elementKey="252949395">InsertPWBRorAOS</NotificationEvent>
      </IntegrationCondition>
   </IntegrationConditions>
</Integration>


What I have tried:

VB.NET code
VB
Dim strEventId As String

strEventId = aobjxmlNotificationEventNode.SelectSingleNode("@elementKey").InnerText

objInsertPWBRorAOS.CompletedDate = CDate(aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate").InnerText)
Posted
Updated 18-Jul-19 12:56pm

1 solution

Quote:
How do I fix this so it works whether or not the CompDate element exist in the XML Document?

Rather simple, either you check that element exist before reading its value, either you read the value to a temp variable and the check if variable is expected object or nothing before storing value.
Should like that:
VB
Tmp= CDate(aobjXmlInputDoc.DocumentElement.SelectSingleNode("Case/CaseEvent[@ID=" + strEventId + "]/CompDate").InnerText)
If Tmp Is Nothing Then objInsertPWBRorAOS.CompletedDate = Tmp
 
Share this answer
 
Comments
Member 11403304 18-Jul-19 19:09pm    
Thanks. I thought about doing it that way then got distracted and forgot.
Patrice T 18-Jul-19 19:15pm    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900