Share via

check an xml node is not nothing

Simon 491 Reputation points
2022-02-17T17:26:13.33+00:00

i am using in vb.net to load an Xml
Dim SrvrSetXml As New XmlDocument()
SrvrSetXml.Load("C:\Users\" & UserNameP() & "\AppData\Roaming\ProgVndr\ProgsOpn.xml")
Dim erPWndXmlFile As XmlNodeList = SrvrSetXml.DocumentElement.SelectNodes("/dataroot/ProgsOpn")
For Each node As XmlNode In erPWndXmlFile
My.MySettings.Default.UnitID2 = (node.SelectSingleNode("UnitID2").InnerText)
Next
if the node is empty it is making an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Xml.XmlNode.SelectSingleNode(...) returned Nothing.

to prevent this error i am trying
if not (node.SelectSingleNode("UnitID2").InnerText) is nothing then
it dosnt help the same error massage appers

Developer technologies | Visual Studio | Debugging

Answer accepted by question author

Yitzhak Khabinsky 27,196 Reputation points
2022-02-17T20:17:40.43+00:00

Hi @Simon ,

Please try the following solution.

VB.NET

Sub Main  
	Const filename As String = "e:\Temp\ProgsOpn.xml"  
	Dim xdoc As XDocument = XDocument.Load(filename)  

	Dim ProgsOpn = xdoc.Descendants("ProgsOpn")  
  
	For Each elem In ProgsOpn.Elements()  
		Console.WriteLine($"{elem.Name}='{elem.Value}'")  
	Next  
  
	Dim el1 As String = xdoc.Descendants("UnitIDO").FirstOrDefault()?.Value  
	Dim el2 As String = xdoc.Descendants("NotExistingElement").FirstOrDefault()?.Value  
	  
	Console.WriteLine($"existing element: {el1}")  
	Console.WriteLine($"not existing element: {el2}")  
End Sub  

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Simon 491 Reputation points
    2022-02-17T18:06:42.863+00:00

    this is the xml sample

    <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ProgsOpn.xsd" generated="2022-02-17T10:56:41">
    <ProgsOpn>
    <ID>1</ID>
    <Unapld>26</Unapld>
    <QuitMain>True</QuitMain>
    <Tnnts>26</Tnnts>
    <TnntID>111132</TnntID>
    <TnntID2>100016</TnntID2>
    <TnntIDO>111140</TnntIDO>
    <Prprty>0</Prprty>
    <PrptID>24</PrptID>
    <PrptID2>100002</PrptID2>
    <PrptIDO>5</PrptIDO>
    <Units>0</Units>
    <UnitID>83</UnitID>
    <UnitIDO>101922</UnitIDO>
    <Stf>26</Stf>
    <StfID>100171</StfID>
    <StfID2>100171</StfID2>
    <StfIDO>100338</StfIDO>
    <Vndrs>26</Vndrs>
    <VndrID>388</VndrID>
    <VndrID2>808</VndrID2>
    <VndrIDO>918</VndrIDO>
    <Workrs>26</Workrs>
    <WorkID>11</WorkID>
    <WorkIDO>437</WorkIDO>
    <OnrIDO>987</OnrIDO>
    <Owners>26</Owners>
    <OwnID>21</OwnID>
    <OwnID2>957</OwnID2>
    <OwnIDO>437</OwnIDO>
    </ProgsOpn>
    </dataroot>

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.