A simple how to read from and write data to a XML document with Microsoft Visual Studio 2008 and Linq. |
|
||
Creating a XML document | ||
To create a XML document | ||
|
||
To call the function and create the XML file in c:\temp\customer.xml
CreateCustomerXMLfile("c:\\temp\\customer.xml"); |
||
Add a record to the Customer XML document | ||
To add a record to the customer xml document we create the following function | ||
#region AddCustomerToXMLfilepublic static string AddCustomerToXMLfile(string XMLfile, string Id, string Name) { XDocument XMLDoc = XDocument.Load(XMLfile); XElement root = XMLDoc.Root; root.Add(new XElement("Customer", new XElement("Id", Id), new XElement("Name", Name))); XMLDoc.Save(XMLfile); return Id; } #endregion |
||
Call the function a new record will be created with id 1 name Mark
AddCustomerToXMLfile("c:\\temp\\Customer.xml","1","Mark"); |
||
Update a record in a XML document | ||
First we create a customer class | ||
#region Customer Classpublic class Customer { public string ID; public string NAME; } #endregion |
||
Next we create the function to update the specific record we will call this function UpdateCustomerInXMLfile. The function wil try to find the Id in the XML document and update it with the Name parameter. |
||
#region UpdateCustomerInXMLfile |
||
Now we are ready to call the update function | ||
UpdateCustomerInXMLfile( "c:\\temp\\Customer.xml", "1", "Johny"); |
||
The name "Mark" will have changed in the XML document to "Johny" | ||
www.programmingsystems.eu |
- Log in to post comments