[quoted text, click to view] "Banski" <the_banski@hotmail.com> wrote in message news:a132e207.0406270800.1d78975f@posting.google.com...
> I cant figure out how to get the value of date with GetAttribute.
: :
> HttpContext.Current.Response.Write("ID = ");
> HttpContext.Current.Response.Write(iterator.Current.GetAttribute("id",
> String.Empty));
> HttpContext.Current.Response.Write(" Date = ");
> HttpContext.Current.Response.Write(iterator.Current.GetAttribute("date",
> String.Empty));
: :
> <article id="2">
> <published date="2004-02-01"/>
First thing that jumps out at me, is the use of the Current XPathNavigator on the
XPathNodeIterator to retrieve both properties without moving. The 'id' and 'date'
attributes are not on the same nodes, therefore, they can't both be available from
Current without it being re-positioned. GetAttribute( ) does not perform a search
on child elements ... it will only look on the element where it has been positioned.
Next, the <published> element is only a child of the <article> element that you've
selected, therefore it won't directly exist in the XPathNodeIterator. The code must
go a level deeper using the Current XPathNavigator to fetch it for itself.
- - -
// . . .
string idValue = iterator.Current.GetAttribute( "id", String.Empty));
if ( idValue.Length != 0 )
{
HttpContext.Current.Response.Write( "ID = ");
HttpContext.Current.Response.Write( idValue);
if ( iterator.Current.MoveToFirstChild( ) ) // [1]
{
System.Diagnostics.Debug.Assert( iterator.Current.LocalName == "published"); // [2]
string dateValue = iterator.Current.GetAttribute( "date", String.Empty));
if ( dateValue.Length != 0 ) // [3]
{
HttpContext.Current.Response.Write( " Date = ");
HttpContext.Current.Response.Write( dateValue);
}
}
}
// . . .
- - -
This replacement for the original code segment quoted above should be a little
more robust.
Key points are:
1. After emitting an attribute value for the 'id' attribute (if there was one), the
XPathNavigator on iterator.Current is advanced to the first child node of
or the <article> element.
2. I make an assertion that my inference of the <publisher> element always
being the first child of <article> is correct. When debugging, the IDDE
will warn me if I'm mistaken (if there's any likelihood the <publisher> element
could be elsewhere; detecting it and possibly throwing an Exception might be
in order).
3. After checking if there is a 'date' attribute on the new element (GetAttribute( )
indicates this by returning a zero-length, empty string), any date value is written
out (additional validation of the date may be in order, using DateTime.Parse( )
and any relevant cultural date time formatting context).
Derek Harmon