May 2, 2009

Safely retrive attribute from XML Node in a Document

In XML processing, we commonly encounter a situation where we require to get the attribute value from a given XML Node. But most of the time it happens that the node may not contain the attribute itself. So if we try to get value of the attribute, runtime will definitely throw the exception. And exceptions are evils for the perfomance of any application.

In such scenario, first we need to check for the existence of the attribute in the XML Node. Here XMLElement class comes for the rescue. XMLElement has a static method HasAttribute which will serve the purpose of checking existence of the attribute in the given XML Node.

Here is the sample which show how to get the attribute value safely

private string GetAttributeValue(XmlNode xNode, string attributeToFind)
{
string returnValue = string.Empty;
XmlElement ele = xNode as XmlElement;

if (ele.HasAttribute(attributeToFind))
returnValue= ele.GetAttribute(attributeToFind);

return returnValue;
}


Hope this will help.

No comments:

Post a Comment