Groups | Blog | Home
all groups > dotnet xml > january 2006 >

dotnet xml : Finding out if attribute X exists with XmlTextReader


Rick Francis
1/24/2006 12:34:41 PM
Gustaf,
The GetAttribute method returns the attribute as string value or null if no
attribute exists. The following should test this condition correctly.


String sAttr = r.GetAttribute("order");
if(sAttr != null)
{
order = Convert.ToDecimal(sAttr);
}
else
{
//do whatever you want when the attribute doesn't exist
}


Good luck...


[quoted text, click to view]

Gustaf
1/24/2006 8:53:08 PM
My docs have attributes called "order", with a default value of 1. So if
there is no "order" attribute, the program shall use the value 1.
Implementing this with XmlTextReader was harder than expected. Since
GetAttribute() returns null if the attribute isn't found, and null can
be interpreted as false, I thought this would do it:

decimal order = 1;
if (r.GetAttribute("order"))
order = Convert.ToDecimal(r.GetAttribute("order"));

I get the error:

Cannot implicitly convert type 'string' to 'bool'

What's the right way to do it?

AddThis Social Bookmark Button