We help IT Professionals succeed at work.

Problem with null records in xml in visual basic

ftopcu
ftopcu asked
on
Medium Priority
401 Views
Last Modified: 2012-05-06
I have e problem with some xml rows.

My xml like
<eventlist>
<event>
<eventnumber>1</eventnumber>
<eventtype>1</eventtype>
</event>
<event>
<eventnumber>2</eventnumber>
</event>
</eventlist>

I dont have eventtype ChildNodes in each row.. but I when I want to get this data I got a error.

When I want to read this xml with  selectnodes like..

m_nodelist = m_xmld.SelectNodes("//eventlist/event")
      
dim lig as xmlnode
 For Each lig In m_xmld.SelectNodes("//eventlist/event")

            console.write(lig("eventtype").InnerText)
next


then I dot a error like this

System.NullReferenceException: Object reference not set to an instance of an object. at ParsingUsingXmlDocument.Main()

how can I know null eventtype rows..
Comment
Watch Question

Ur second 'event' row does not contain 'eventtype' element in it. Hence the error. Simply put an if condition to check 'eventtype' element exists in the node or not. Other way to do it is put whole "//eventlist/event/eventtype" in ur XPath query... Check the code below


'''******Using if condition
Dim objDocument As New XmlDocument
        objDocument.Load("C:\Documents and Settings\Administrator\Desktop\Test.xml")
        For Each objNode As XmlNode In objDocument.SelectNodes("//eventlist/event")
            If Not objNode("eventtype") Is Nothing Then
                Console.Write(objNode.Value)
            End If
        Next
 
 
'''******Using "//eventlist/event/eventtype" xpath
 
Dim objDocument As New XmlDocument
        objDocument.Load("C:\Documents and Settings\Administrator\Desktop\Test.xml")
        For Each objNode As XmlNode In objDocument.SelectNodes("//eventlist/event/eventtype")
            Console.Write(objNode.Value)
        Next

Open in new window

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
 If Not objNode("eventtype") Is Nothing Then
                Console.Write(objNode("eventtype").InnerText)
   End If


its solved my problem ..
Thanx
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.