Updating existing XML attribute

G

Guest

This should be easy, and it probably is, I just can't find anything on it.

I have to build an XML Document object in memory, add some child nodes, save
it, and then if another condition arises, reload the same xml document and
append some more child nodes. And by the way, the user requires that I save
between all these occurances so I can't just leave it in memory and then save
it just once.

So far everything works exactly as I need it to with one exception. There
is an attribute on the Root that has a count of each of the child nodes. I
get it set to an original value of 0, but have so far been unable to figure
out how to get it updated. Here's the relevent code:

if (cwaCount == 0)
{
// Write the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0",
"utf-8", null);

// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("cwa_blocks");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
rootNode.SetAttribute("Count", cwaCount.ToString());
xmlDoc.AppendChild(rootNode);
}
else
{
xmlDoc.Load(eventDir + @"\cwa.xml");
}
// Create a new <cwa> element and add it to the root node
XmlElement parentNode = xmlDoc.CreateElement("cwa");
xmlDoc.DocumentElement.PrependChild(parentNode);
//OTHER PROCESSING TO ADD CHILD NODES THAT WORKS

//Save file
xmlDoc.Save(eventDir + @"\cwa.xml");

cwaCount++;
XmlElement root = xmlDoc.DocumentElement;
XmlAttribute attr = root.GetAttributeNode("Count");

//OBVIOUSLY SOMETHING WRONG HERE...THE attr NEVER UPDATES
attr.InnerXml = cwaCount.ToString();

I've tried updating a number of ways, but none have worked so far.
Any help greatly appreciated.

WhiteWizard
aka Gandalf
MCSD.NET, MCAD, MCT
 
M

Martin Honnen

WhiteWizard wrote:

cwaCount++;
XmlElement root = xmlDoc.DocumentElement;
XmlAttribute attr = root.GetAttributeNode("Count");

//OBVIOUSLY SOMETHING WRONG HERE...THE attr NEVER UPDATES
attr.InnerXml = cwaCount.ToString();

xmlDoc.DocumentElement.SetAttribute("Count", cwaCount.ToString());
should suffice, much the same as you did some lines before. No need to
first access the attribute as a node.
If you have an XmlAttribute instance then to change its value you do e.g.
attr.Value = cwaCount.ToString();
but usually calling SetAttribute on the element suffices.
 
G

Guest

NEVER MIND!!!!

I'm having a senior moment.

I just realized when looking over my posting that the update was AFTER the
save. In my defense I'm writing to a remote memory module AND a local hard
drive, and didn't notice that I was already past the RMM save.

Just a VERY long week.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top