Code Snippet: How to read and modify an XML file programmatically
September 9th, 2011
STEP 1: Create an XML file on your local machine
<?xml version="1.0" encoding="utf-8"?> <Address> <Address1>One Microsoft Way</Address1> <City>Redmond</City> <State>WA</State> <Zip>98035</Zip> </Address> |
STEP 2: Create a class with public properties to change the XML
public class Address { public string Address1; public string Address2; public string City; public string State; public string Zip; } |
STEP 3: Create an event to handle the XML serialization
private void btnSerializeXMLFile_Click(object sender, EventArgs e) { Address _address = new Address(); XmlSerializer serializer = new XmlSerializer(typeof(Address)); FileStream file = new FileStream(@"TestXML.xml", FileMode.Open); _address = serializer.Deserialize(file) as Address; file.Close(); _address.Zip = "30005"; TextWriter writer = new StreamWriter(@"TestXML.xml"); serializer.Serialize(writer, _address); writer.Close(); } |
