matthew king

matthew king

  • NA
  • 52
  • 0

updating xml data

Mar 20 2010 1:22 PM

Sir/Ma'am,
I'm trying to modify existing XML data.  For example, I have an xml file in the following format:

<?xml version="1.0" encoding="utf-8" ?>
<cars>
  <car>
    <vin>1255588</vin>
    <color>red</color>
    <engine>I4</engine>
    <type>sedan</type>
    <price>11000</price>
  </car>
  <car>
    <vin>388854</vin>
    <color>blue</color>
    <engine>V6</engine>
    <type>coupe</type>
    <price>09999</price>
  </car>
  <car>
    <vin>214569</vin>
    <color>green</color>
    <engine>V8</engine>
    <type>truck, full</type>
    <price>05000</price>
  </car>
</cars>
I also have a form with 1 combobox (e.g vin.text) and 4 text boxes (e.g. color.text, engine.text, type.text, and price.text), which corresponds to the xml nodes. I'm attempting to write a method that will update the xml data, if it corresponds to the vin number. So, if I want to change the price on vin 1255588 from 11000 to 09999, how could I accomplish that? 
heres my code:

        private void button1_Click(object sender, EventArgs e)
        {
   try
   {
    XmlTextReader reader = new XmlTextReader(@"C:\test.xml");
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    reader.Close();
    
    //Select the vin node
    XmlNode oldvin;
    XmlElement root = doc.DocumentElement;
                oldvin = root.SelectSingleNode("/cars/car/[vin='" + vin.Text + "']");
    XmlElement newCd = doc.CreateElement("car");
    newCd.SetAttribute("vin", vin.Text);
    
    newCd.InnerXml = "<vin>" + vin.Text + "</vin>" +
     "<color>" + color.Text + "</color>" +
     "<engine>" + engine.Text + "</engine>" +
                 "<type>" + type.Text + "</type>" +
     "<price>" + price.Text + "</price>";
     
    root.ReplaceChild(newCd, oldvin);
    //save the output back to the xml file
    doc.Save(@"C:\test.xml");
    this.DialogResult = DialogResult.OK;
   }
   catch (Exception ex)
   {
    Console.WriteLine ("Exception: {0}", ex.ToString());
    this.DialogResult = DialogResult.Cancel;
   }
  }
        }
    }

Answers (1)