Update / Edit XML Error


  • Hello,

    I am using 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"?>
        <name id="1" type="card">bob</name>
        <name id="2" type="card">Jack</name>
        <name id="3" type="card">John</name>

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

    I am using the following 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()
            ' 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"
                ' Where's Bob?
                MessageBox.Show("Can't find id.", "missing?", MessageBoxButtons.OK, _
            End If
            ' Save the Xml.

    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?

    Friday, February 15, 2013 5:27 AM


  • 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"

    • Marked as answer by Aaron-King Friday, February 15, 2013 6:39 AM
    Friday, February 15, 2013 6:31 AM