本文讲解如何安全解析包含 HTML 实体(如 )的 XML 字符串,提取 <parameterizedString> 中的转义 HTML 内容,并动态构建结构化 HTML 表格,避免 DOM 解析错误与 XSS 风险。 本文讲解如何安全解析包含 html 实体(如 `<`、`>`)的 xml 字符串,提取 `` 中的转义 html 内容,并动态构建结构化 html 表格,避免 dom 解析错误与 xss 风险。在前端开发中,常需处理嵌套了 HTML 片段的 XML 数据(例如测试用例导出格式),其中 <parameterizedString> 标签内容常以 HTML 实体形式编码(如 Action Field 001)。直接使用 DOMParser 解析原始 XML 字符串时,若实体未被预处理或上下文不匹配,极易触发解析错误(如 parsererror 或空文档)。关键在于:XML 解析器本身能正确识别实体(前提是文档类型声明合规),但 textContent 返回的是已解码后的纯文本,而我们需要的是可渲染的 HTML 结构------此时应将解码后的内容作为 HTML 插入,而非文本。以下为推荐实现方案(无需手动编写复杂解码函数):const strXML = `<steps id="0" last="4"> <step id="1" type="ValidateStep"> <parameterizedString isformatted="true"><DIV><P>Action Field 001</P></DIV></parameterizedString> <parameterizedString isformatted="true"><DIV><P>Expected Result Field 001</P></DIV></parameterizedString> <description/> </step> <step id="2" type="RunStep"> <parameterizedString isformatted="true"><DIV><P>Action Field 002</P></DIV></parameterizedString> <parameterizedString isformatted="true"><DIV><P>Expected Result Field 002</P></DIV></parameterizedString> <description/> </step></steps>`;// ? 正确:使用 application/xml 解析 XML(DOMParser 原生支持实体解码)const doc = new DOMParser().parseFromString(strXML, "application/xml");if (doc.querySelector("parsererror")) { throw new Error("XML parsing failed: " + doc.querySelector("parsererror").textContent);}// 提取所有 step 元素const steps = ...doc.querySelectorAll('step');// 创建表格结构const table = document.createElement("table");const tbody = document.createElement("tbody");steps.forEach(step => { const row = document.createElement("tr"); // 第一列:step 类型(type 属性) const typeCell = document.createElement("td"); typeCell.textContent = step.getAttribute("type") || "unknown"; // 第二列:parameterizedString 的内容(已自动解码为 HTML 字符串) const htmlContent = step.querySelector("parameterizedString")?.textContent || ""; const contentCell = document.createElement("td"); contentCell.innerHTML = htmlContent; // ?? 注意:仅当内容可信时才用 innerHTML row.append(typeCell, contentCell); tbody.append(row);});table.append(tbody);document.body.append(table);配套样式(增强可读性): 唱鸭 音乐创作全流程的AI自动作曲工具,集 AI 辅助作词、AI 自动作曲、编曲、混音于一体
相关推荐
这个DBA有点耶9 分钟前
数据库迁移灰度验证:从读流量到双写再到全量切换的完整路径Wang's Blog14 分钟前
PostgreSQL笔记16: 索引基础——概念、类型、创建与最佳实践用户31693538118323 分钟前
"批量"删除-sqlAAA@峥40 分钟前
Python 基础开篇:认识 Python、版本选择、环境部署与首个 HelloWorldMetaphor6921 小时前
使用 Python 快速在 Word 文档中插入图片瀚高PG实验室1 小时前
SQL优化案例:使用分区表优化SQL查询性能SelectDB1 小时前
15 分钟搭建 PostgreSQL + Apache Iceberg + Apache Doris 的湖仓分析平台2601_966871401 小时前
Python 爬虫 + 数据挖掘实战:数据抓取与深度挖掘分析全流程SelectDB1 小时前
科大讯飞可观测性底座:从 ES/Loki 到 Apache Doris 的可观测存储分析升级实践青禾8371 小时前
Linux 系统信息、权限管理与 Python 并发编程(协程与线程)完全指南