I have the following XML file, which I intend to use to read and save to it.
------------------------------------------------------------------
------------------------------------------------------------------
The nodes are self closing and each one has 1 attribute.
Sometimes I just want to read this attribute and show on the page, other times I want to read it add +1 and save it.
I just want to say, read node of name xxxx and give me its attribute value.
What would be the best and simplest way to do this in C#?
I have been playing around with XmlTextReader/Writer and cant get this to work, also tried many other approaches, all failed.
Thanks.
John SeacadaPosted Nov 6, 2007, 5:29 PM
Works beautifuly, thanks, just one more question; what are the implications of having some pages that will have to read the counters all the time and other pages that will need to write the xml, will that cause problems? I mean constant and simultaneous read/write out of the same file?
Thanks once again.
AlanPosted Nov 6, 2007, 12:03 PM
Here's some straightforward code which should do what you want:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("john.xml"); // load xml file
XmlNode baseNode = doc.DocumentElement; // get 'Base' node which is the root
string searchName = "John"; // look for child node named 'John'
XmlNode childNode = baseNode[searchName]; // get child node
XmlAttribute attribute = childNode.Attributes[0]; // get first and only attribute
// display name and value of attribute to console
Console.WriteLine("Name: {0}", attribute.Name);
Console.WriteLine("Value: {0}", attribute.Value);
// add one to value and over-write file with amended document
attribute.Value = (int.Parse(attribute.Value) + 1).ToString();
doc.Save("john.xml");
// press return to end program
Console.ReadLine();
}
}