Select node with xpath

I want to go to a deep link for the xml with xpath, and also there is a name space in it. Currently I have:

XmlNode link = xmlDoc
    .SelectSingleNode("dn:feed", nsmgr)
    .SelectSingleNode("dn:entry", nsmgr)
    .SelectSingleNode("dn:link", nsmgr);

This works fine, but since the path is very long I just want to use kind of xpath like:

XmlNode link = xmlDoc.SelectSingleNode("dn:feed/entry/link", nsmgr);

But this does not works.

Jon Skeet
people
quotationmark

I suspect this is a namespace problem. You're only specifying the namespace for the feed element, not for entry or link. Try this:

XmlNode link = xmlDoc.SelectSingleNode("dn:feed/dn:entry/dn:link", nsmgr);

Personally I'd use LINQ to XML if possible though - aside from being a generally nicer API than XmlDocument, it makes it really easy to work with namespaces:

XDocument doc = ...;
XNamespace dn = "...";
XElement link = doc.Element(dn + "feed")
                   .Element(dn + "entry")
                   .Element(dn + "link");

I prefer expressing what I'm looking for (attributes, elements etc, with conditions where appropriate) in code rather than in XPath. Your mileage may vary, of course.

people

See more on this question at Stackoverflow