Answered Update / Edit XML Error

  • Friday, February 15, 2013 5:27 AM
     
      Has Code

    Hello,

    I am using VB.net and I am trying to update / edit a node value in a XML file.

    My XML file Looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <Root>
      <Names>
        <name id="1" type="card">bob</name>
        <name id="2" type="card">Jack</name>
        <name id="3" type="card">John</name>
      </Names>
    </Root>

    Lets say I am trying to edit 'Jack' in my XML file.

    I am using the following VB.net code:

            Dim file As String
            Dim file_name As String = Application.StartupPath
            file = file_name.Substring(0, file_name.LastIndexOf("\")) & "\settings.xml"
    
            ' Load the XmlDocument.
            Dim xd As New XmlDocument()
            xd.Load(file)
    
            ' Find the node where the Person's attribute ID is 1.
            Dim nod As XmlNode = xd.SelectSingleNode("/Root/Names/name[@id='2']")
            If nod IsNot Nothing Then
                ' Change the InnerText of the age node.
                nod.ChildNodes(2).InnerText = "Tom"
            Else
                ' Where's Bob?
                MessageBox.Show("Can't find id.", "missing?", MessageBoxButtons.OK, _
                    MessageBoxIcon.Information)
            End If
    
            ' Save the Xml.
            xd.Save(file)

    but I get a error that says: Object reference not set to an instance of an object.

    as shown below:

    Anyone know what I am doing wrong?

All Replies

  • Friday, February 15, 2013 6:31 AM
     
     Answered Has Code

    Is the example XML correct as there is no age child element in  name element?

    If you just try to change the name, then you don't need to access ChildNodes as there is no any.

    If nod IsNot Nothing Then
     nod.InnerText = "Tom"
    Else

    • Marked As Answer by Aaron-King Friday, February 15, 2013 6:39 AM
    •