using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Web;
using
System.Web.Mvc;
using
System.Xml.Linq;
using
System.Web.Routing;
namespace
TestMvc3
{
public
class
MvcSiteMap
{
private
static
XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath(
@"~/SiteMap.xml"
));
private
UrlHelper url =
null
;
private
string
currentURL =
""
;
public
MvcSiteMap()
{
url =
new
UrlHelper(HttpContext.Current.Request.RequestContext);
currentURL = url.RouteUrl(HttpContext.Current.Request.RequestContext.RouteData.Values).ToLower();
}
public
MvcHtmlString Navigator()
{
XElement c = FindNode(doc.Root);
Stack<XElement> temp = GetPath(c);
return
MvcHtmlString.Create(BuildPathString(temp));
}
private
string
GetNodeUrl(XElement c)
{
return
url.Action(c.Attribute(
"action"
).Value, c.Attribute(
"controller"
).Value,
new
{ area = c.Attribute(
"area"
).Value });
}
private
string
BuildPathString(Stack<XElement> m)
{
StringBuilder sb =
new
StringBuilder();
TagBuilder tb;
TagBuilder tc =
new
TagBuilder(
"span"
);
tc.SetInnerText(
">>"
);
string
sp = tc.ToString();
int
count = m.Count;
for
(
int
x = 1; x <= count; x++)
{
XElement c = m.Pop();
if
(x == count)
{
tb =
new
TagBuilder(
"span"
);
}
else
{
tb =
new
TagBuilder(
"a"
);
tb.MergeAttribute(
"href"
, GetNodeUrl(c));
}
tb.SetInnerText(c.Attribute(
"title"
).Value);
sb.Append(tb.ToString());
sb.Append(sp);
}
return
sb.ToString();
}
private
Stack<XElement> GetPath(XElement c)
{
Stack<XElement> temp =
new
Stack<XElement>();
while
(c !=
null
)
{
temp.Push(c);
c = c.Parent;
}
return
temp;
}
private
bool
IsUrlEqual(XElement c)
{
string
a = GetNodeUrl(c).ToLower();
return
a == currentURL;
}
private
XElement RecursiveNode(XElement node)
{
foreach
(XElement c
in
node.Elements())
{
if
(IsUrlEqual(c) ==
true
)
{
return
c;
}
else
{
XElement x = RecursiveNode(c);
if
(x !=
null
)
{
return
x; }
}
}
return
null
;
}
private
XElement FindNode(XElement node)
{
if
(IsUrlEqual(node) ==
true
)
{
return
node;
}
else
{
return
RecursiveNode(node);
}
}
}
}