Finding XmlNode by attribute in ASP.net

I am trying to write code to find a specific XmlNode object based on a URL in an XML sitemap, but cannot find anything.

Sitemap is a standard ASP.net sitemap and contains:

<siteMapNode url="~/lev/index.aspx" title="Live-Eye-Views">
--- Child Items ---
</siteMapNode>

      

The code I'm using to find an item:

XmlDocument siteMapXml = new XmlDocument();
siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName)
XmlNode levRoot = siteMapXml.SelectSingleNode("siteMapNode[@url=\"~/lev/index.aspx\"]");

      

The levRoot object is always zero. When I break down after the Load method, I can see all the elements in the XML file so that it loads as expected.

I tried using single quotes in the XPath query, but it didn't make any difference.

_siteMapFileName is set in the Initialize method and points to the correct file.

Does anyone have any ideas what might be wrong with this or suggest another way to find a specific element by attribute?

0


source to share


4 answers


The sitemap has a default namespace, but you are not linking to it.

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="~/lev/index.aspx" title="Live-Eye-Views">
    <!-- Child Items -->
  </siteMapNode>
</siteMap>

      



So, you have to use this:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(siteMapXml.NameTable);
nsmgr.AddNamespace("smap", "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");
string xpath = "//smap:siteMapNode[@url=\"{1}\"]";
string url = "~/lev/index.aspx";
XmlNode levRoot = siteMapXml.SelectSingleNode(String.Format(xpath, url), nsmgr);

      

+2


source


Try adding "//" to the beginning of your XPath query to match any siteMapNode with the correct url, not just the top level.

(I'm not familiar with the XML format of the ASP.NET sitemap, so it might not make any difference ...)



EDIT: I suggest you use the XPath testing tool (there are many - I haven't used them myself since I rarely need XPath expressions). They will let you load into your document and then show you what XPath does. It looks good, so it's very strange ...

+1


source


looks good afaik, have you tried using xpath like:

** // ** SiteMapNode [@URL = "~ / leva / index.aspx"]

0


source


The sitemap file contains the top level "siteMap" node, which can contain one "siteMapNode" node. This "siteMapNode" can contain an arbitrarily deep tree of child nodes "siteMapNode".

When adding "//" make sure node is getting matches, this is a sloppy and dangerous habit. If you know where a node can be found in an XML document, it is best to match more explicitly.

In this case, let's say the node you want is at the top of the tree that XPath requires, probably "siteMap / siteMapNode / siteMapNode [@url = \" ~ / lev / index.aspx \ "]" .

0


source







All Articles