# transform.XMLEscape
> 返回删除不允许的字符后再转义为对应 XML 形式的给定字符串。
- 官方英文原文：https://gohugo.io/functions/transform/xmlescape/
- 本页规范地址：https://hugozh.cn/functions/transform/xmlescape/
- 最近更新：2026-10-02
- 最后提交：912b1d3 chore(site): 添加 static/CNAME（hugozh.cn），供 GitHub Pages 等平台绑定自定义域名
- 签名：transform.XMLEscape INPUT
- 返回类型：string
- 站点：Hugo 中文文档（https://hugozh.cn/）· 社区维护的非官方中文翻译，如有出入以官方英文原文为准

---
`transform.XMLEscape` 函数先删除 XML 规范中定义的[不允许的字符][]，再把结果中的以下字符替换为 [HTML 实体][]来完成转义：

- `"` → `&#34;`
- `'` → `&#39;`
- `&` → `&amp;`
- `<` → `&lt;`
- `>` → `&gt;`
- `\t` → `&#x9;`
- `\n` → `&#xA;`
- `\r` → `&#xD;`

例如：

```go-html-template
{{ transform.XMLEscape "<p>abc</p>" }} → &lt;p&gt;abc&lt;/p&gt;
```

在由 Go 的 [`html/template`][] 包渲染的模板中使用 `transform.XMLEscape` 时，请把该字符串声明为安全 HTML，以免二次转义。例如在 RSS 模板中：

```xml {file="layouts/rss.xml"}
<description>{{ .Summary | transform.XMLEscape | safeHTML }}</description>
```

[HTML 实体]: https://developer.mozilla.org/en-US/docs/Glossary/Entity
[`html/template`]: https://pkg.go.dev/html/template
[不允许的字符]: https://www.w3.org/TR/xml/#charsets

