Monday, September 25, 2006

XPathNavigator missing SetAttribute

I have been using XPathNavigator for several weeks now. Early on I found out that it's a very usefull class. Microsoft did made GetAttribute and CreateAttribute. So where is SetAttribute?

The following function combines the two existing methods to support the SetAttribute.


void SetAttribute(
System.Xml.XPath.XPathNavigator navigator,
String prefix, String localName,
String namespaceURI,
String value)
{
if (navigator.CanEdit == true)
{
// Check if given localName exist
if (navigator.MoveToAttribute(localName, namespaceURI))
{
// Exist, so set current attribute with new value.
navigator.SetValue(value);
// Move navigator back to beginning of node
navigator.MoveToParent();
}
else
// Does not exist, create the new attribute
navigator.CreateAttribute(prefix, localName, namespaceURI, value);
}
}


Happy coding,

Edwin

3 comments:

leomrlt said...

Thanks man. Really useful method !

Gareth said...

Thank you, very useful!

Sachin said...

Very very helpful.