C# .NET - xml - Asked By Mahesh B on 07-Feb-12 07:09 AM

write to xml file in a specific node in c#
Venkat K replied to Mahesh B on 07-Feb-12 07:27 AM
Load the xml and assign the value to node as shown below:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="New Value";

Thanks
Somesh Yadav replied to Mahesh B on 07-Feb-12 07:50 AM
Hi mahesh i will explain you with an example

I have a xml database with the following format:

<Students>
 
<Student ID= *GUID NUMBER*>
 
<FullName>John Smith</FullName>
 
<Address>Blah blah blah</Address>
  and so on...
 
<Student ID= *GUID NUMBER*>
 
<FullName>Joe Blow</FullName>
 
<Address>Blah Blah</Address>
  and so on...
I have a combobox that will select from this xml data to display the FullName in its dropdown. Now what I need to do is have other fields to update and add nodes to the chosen Student based on what FullName is chosen in the combobox, once another button - "Submit" is pressed

To select your specific Student node, you could do:

XmlDocument xml = new XmlDocument();
xml
.LoadXml("<Students>...."); // or xml.Load("yourfile.xml");
XmlElement student = xml.SelectSingleNode(
   
String.Format("//Student[@ID='{0}']",
                  yourcombo
.SelectedItem.Value)) as XmlElement;
if(student != null)
{
   
XmlElement another = xml.CreateElement("another");
    another
.InnerText = "Value";
    student
.AppendChild(another);

   
// do other stuff
}

i hope it helped you a lot to understand the concept.