"""Offline ASP.NET WebForms verifier for Chapter 54 (navigation)."""
from __future__ import annotations
import html
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline ASP.NET WebForms verifier (IIS/ASP.NET runtime absent)"
WEB_SITEMAP_XML = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<siteMap>
<siteMapNode title="Home" url="/aspnet/w3home.aspx">
<siteMapNode title="Services" url="/aspnet/w3services.aspx">
<siteMapNode title="Training" url="/aspnet/w3training.aspx"/>
<siteMapNode title="Support" url="/aspnet/w3support.aspx"/>
</siteMapNode>
</siteMapNode>
</siteMap>
"""
def parse_sitemap(xml_text: str) -> dict[str, object]:
root = ET.fromstring(xml_text)
if root.tag != "siteMap":
raise ValueError("Root element must be <siteMap>")
top_nodes = list(root)
if len(top_nodes) != 1 or top_nodes[0].tag != "siteMapNode":
raise ValueError("<siteMap> must contain exactly one top-level <siteMapNode>")
def to_node(elem: ET.Element) -> dict[str, object]:
title = elem.attrib.get("title", "").strip()
url = elem.attrib.get("url", "").strip()
if not title or not url.startswith("/"):
raise ValueError(f"Invalid siteMapNode attributes: title={title!r}, url={url!r}")
return {
"title": title,
"url": url,
"children": [to_node(child) for child in elem if child.tag == "siteMapNode"],
}
return to_node(top_nodes[0])
def render_menu_html(node: dict[str, object]) -> str:
children = node["children"]
link = f'<a href="{html.escape(str(node["url"]), quote=True)}">{html.escape(str(node["title"]))}</a>'
if not children:
return f"<li>{link}</li>"
sub = "".join(render_menu_html(c) for c in children)
return f"<li>{link}<ul>{sub}</ul></li>"
def render_treeview_lines(
node: dict[str, object],
*,
collapsed: set[str],
depth: int = 0,
) -> list[str]:
children = node["children"]
title = str(node["title"])
if children:
marker = "+" if title in collapsed else "-"
else:
marker = "*"
lines = [f"{' ' * depth}[{marker}] {title}"]
if children and title not in collapsed:
for child in children:
lines.extend(render_treeview_lines(child, collapsed=collapsed, depth=depth + 1))
return lines
def find_breadcrumb_path(node: dict[str, object], target_url: str) -> list[dict[str, str]] | None:
current = {"title": str(node["title"]), "url": str(node["url"])}
if current["url"].lower() == target_url.lower():
return [current]
for child in node["children"]:
sub = find_breadcrumb_path(child, target_url)
if sub is not None:
return [current] + sub
return None
def render_sitemappath(node: dict[str, object], current_url: str) -> str:
trail = find_breadcrumb_path(node, current_url)
if not trail:
return ""
segments = []
for idx, item in enumerate(trail):
if idx < len(trail) - 1:
segments.append(f'<a href="{html.escape(item["url"], quote=True)}">{html.escape(item["title"])}</a>')
else:
segments.append(f"<span>{html.escape(item['title'])}</span>")
return " > ".join(segments)
def main() -> None:
tree = parse_sitemap(WEB_SITEMAP_XML)
two_roots_rejected = False
try:
parse_sitemap(
'<siteMap><siteMapNode title="A" url="/a.aspx"/><siteMapNode title="B" url="/b.aspx"/></siteMap>'
)
except ValueError:
two_roots_rejected = True
menu_html = f'<ul id="menu1">{render_menu_html(tree)}</ul>'
tv_expanded = render_treeview_lines(tree, collapsed=set())
tv_collapsed = render_treeview_lines(tree, collapsed={"Services"})
crumb_training = render_sitemappath(tree, "/aspnet/w3training.aspx")
crumb_typo = render_sitemappath(tree, "/aspnet/w3trainning-typo.aspx")
cases = [
{
"name": "validate_web_sitemap_rules",
"summary": "解析 web.sitemap 并校验唯一根 <siteMapNode> 及相对根路径 URL 规则,拦截双根节点",
"expected": {
"root_title": "Home",
"services_children": ["Training", "Support"],
"two_roots_rejected": True,
},
"actual": {
"root_title": tree["title"],
"services_children": [c["title"] for c in tree["children"][0]["children"]],
"two_roots_rejected": two_roots_rejected,
},
"passed": (
tree["title"] == "Home"
and [c["title"] for c in tree["children"][0]["children"]] == ["Training", "Support"]
and two_roots_rejected is True
),
},
{
"name": "render_menu_from_sitemap_datasource",
"summary": "模拟 SiteMapDataSource(nav1) 驱动 <asp:Menu> 渲染嵌套导航列表",
"expected": {
"link_count": 4,
"has_training_link": True,
},
"actual": {
"link_count": menu_html.count("<a href="),
"has_training_link": '<a href="/aspnet/w3training.aspx">Training</a>' in menu_html,
},
"passed": (
menu_html.count("<a href=") == 4
and '<a href="/aspnet/w3training.aspx">Training</a>' in menu_html
),
},
{
"name": "render_treeview_expand_collapse",
"summary": "模拟 <asp:TreeView> 的 +/- 展开与折叠状态切换,折叠 Services 时隐藏 Training 与 Support",
"expected": {
"expanded": ["[-] Home", " [-] Services", " [*] Training", " [*] Support"],
"collapsed": ["[-] Home", " [+] Services"],
},
"actual": {
"expanded": tv_expanded,
"collapsed": tv_collapsed,
},
"passed": (
tv_expanded == ["[-] Home", " [-] Services", " [*] Training", " [*] Support"]
and tv_collapsed == ["[-] Home", " [+] Services"]
),
},
{
"name": "render_sitemappath_breadcrumbs",
"summary": "验证 <asp:SiteMapPath> 直接读取 web.sitemap 生成面包屑路径,且 URL 拼写错误时不匹配显示为空",
"expected": {
"training_crumb": '<a href="/aspnet/w3home.aspx">Home</a> > <a href="/aspnet/w3services.aspx">Services</a> > <span>Training</span>',
"typo_crumb": "",
},
"actual": {
"training_crumb": crumb_training,
"typo_crumb": crumb_typo,
},
"passed": (
crumb_training
== '<a href="/aspnet/w3home.aspx">Home</a> > <a href="/aspnet/w3services.aspx">Services</a> > <span>Training</span>'
and crumb_typo == ""
),
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。
入口文件:projects/aspnet-navigation-lab/explore-navigation.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-navigation.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2794.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2817.zip