How to select ChildNodes by name ?

  • Thread starter Thread starter craigkenisston
  • Start date Start date
C

craigkenisston

Hi,

I'm pretty newbie on XML so I have this basic question.
I have a node which has 5 ChildNodes :

<RelatedLink>
<DataUrl type="canonical">clickhere2.com/</DataUrl>
<NavigableUrl>http://clickhere2.com/</NavigableUrl>
<Asin>B0000A1I5E</Asin>
<Relevance>301</Relevance>
<Title>ClickHere2 Network</Title>
</RelatedLink>

My code is :

XmlNodeList xmlnodes =
xmldoc.GetElementsByTagName("RelatedLink");

foreach(XmlNode node in xmlnodes)
{
XmlNode xnav = node.ChildNodes.SelectSingleNode("NavigableUrl");
}

The last line does not work, of course, but that's the idea of what I'm
trying to do. I know I can do something like "node.ChildNodes[1]" to
get the value, but I can't relay on the node position because the data
can miss one or more inner nodes.

Any idea ?
 
I believe the problem is that you are using SelectSingleNode on the children
of RelatedLink. Since each of the children have no children of their own the
result is null.

You should use the following instead:

XmlNodeList links = xmldoc.DocumentElement.SelectNodes("RelatedLink");
foreach(XmlNode child in links)
{
XmlNode urlNode = child.SelectSingleNode("NavigableUrl");
if (urlNode != null)
...
};

Of course there are other ways to find the nodes too including combining the
2 selects into one but I find the above approach the easiest.

Hope this helps,
Michael Taylor, MCP, MCAD - 6/29/05
 
Back
Top