XML can sometimes be a bit confusing, so here are some tips to help you work with XML files.
First, you need to make sure your XML is really XML.
It needs to look like this (the ?xml prefix at the beginning is necessary):
<?xml version="1.0" encoding="UTF-8"?> <Ride> <VehicleInfo> <VehicleMake>Tesla</VehicleMake> <VehicleModel>S</VehicleModel> <VIN>862462032347916</VIN> <ModelYear>2018</ModelYear> <YearPurchased>2017</YearPurchased> </VehicleInfo> </Ride>
In a Xojo project, I put the above in a constant called kXML.
Now you can parse it to get the XmlNode that points to what you want to change. One way is to directly refer to it like this:
Dim xml As New XmlDocument xml.LoadXml(kXML) // Get <VehicleInfo> Dim vehicleInfo As XmlNode // xml.Firstchild is <Ride> and its FirstChild is <VehicleInfo> vehicleInfo = xml.FirstChild.FirstChild // Get <VehicleModel> // This is the 2nd (0-based so use 1) child of <VehicleInfo> Dim vehicleModel As XmlNode vehicleModel = vehicleInfo.Child(1) // Get value for <VehicleModel>'s child which is "S" Dim vehicleModelValue As String = vehicleModel.FirstChild.Value // Change value for <VehicleModel>'s child vehicleModel.FirstChild.Value = "3" // The updated XML which you can use, save, etc. Dim newXML As String = xml.ToString
As an alternative to the above you could search directly for the node you want and then change it. You would do that using Xql:
Dim xml As New XmlDocument xml.LoadXml(kXML) // Search entire XML document for anything that contains <VehicleModel> and // get the results back as a list. Dim vehicleModels As XmlNodeList vehicleModels = xml.Xql("//VehicleModel") If vehicleModels.Length >= 0 Then // At least one <VehicleModel> was found so change the first one's value // Change value for <VehicleModel> vehicleModels.Item(0).FirstChild.Value = "3" End If Dim newXML As String = xml.ToString
For reference:
- XMLDocument class
- XMLNode class
- XMLNodeList class
- User Guide: XML Documents topic