XML

Making Changes to the Data

Now that we have seen how to save data as XML and how to open XML data using ADO, we will look at how to make changes to the XML data. We will start by writing code to open the Products.xml file we created, and then we'll make changes to the data. Once the changes are made, we will call the Update method of the recordset. When the changes are complete, we will save the new data to a file called ProductsUpdate.xml. First add another command button called cmdMakeChanges to the form with a caption Make Changes. Add the following code to the click event handler of the command button cmdMakeChanges:

  Private Sub cmdMakeChanges_Click()
      Dim objNWRecordset As ADODB.Recordset
      Set objNWRecordset = New ADODB.Recordset
      'Open the recordset to a file as XML
      objNWRecordset.Open "C:\Products.XML", Options:=adCmdFile
      objNWRecordset.Fields("ProductName") = "Test"
      objNWRecordset.Update
      objNWRecordset.MoveLast
      objNWRecordset.Delete
      objNWRecordset.Update
      objNWRecordset.Filter = adFilterPendingRecords
      objNWRecordset.Save "c:\ProductsUpdate.xml", adPersistXML
  End Sub

In this case, we have changed the product name of the first record to Test and deleted the last record. The changed recordset is then saved to the ProductUpdate.xml file. You can see the following new additions in the ProductUpdate.xml file after clicking the Make Changes command button:

  
  <rs:update>
     <rs:original>
        <z:row ProductID='1' ProductName='Chai' SupplierID='1'
           CategoryID='1' QuantityPerUnit='10 boxes x 20 bags'
           UnitPrice='18' UnitsInStock='39' UnitsOnOrder='0'
           ReorderLevel='10' Discontinued='False'/>
     </rs:original>
        <z:row ProductName='Test'/>
  </rs:update>
  
  <rs:delete>
     <z:row ProductID='77' ProductName='Original Frankfurter grne Soe'
        SupplierID='12' CategoryID='2' QuantityPerUnit='12 boxes'
        UnitPrice='13' UnitsInStock='32' UnitsOnOrder='0'
        ReorderLevel='15' Discontinued='False'/>
  </rs:delete>

With the updated XML file, ADO can reconstruct a recordset that has the original and new values for fields that are edited and can determine which rows have been deleted. Now let's look at how we would actually update the data source.