在XSL中插入Google Tag Manager脚本遇标签匹配错误的解决咨询
问题描述
使用xmlstarlet生成HTML原本正常,但在XSL文件中添加以下Google Tag Manager脚本后出现标签匹配错误:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX'); </script>
报错信息如下:
current.xsl:26.87: Opening and ending tag mismatch: head line 8 and script pt async src="https://www.googletagmanager.com/gtag/js?id=G-QK0NG2KM96"></script ^ current.xsl:28.10: Opening and ending tag mismatch: html line 7 and head </head> ^ current.xsl:120.9: Opening and ending tag mismatch: template line 5 and html </html> ^ current.xsl:121.16: Opening and ending tag mismatch: stylesheet line 2 and template </xsl:template> ^ current.xsl:122.1: Extra content at the end of the document </xsl:stylesheet>
推测问题出在async属性不符合XML规范,寻求解决办法。
解决办法
1. 修正async属性的XML写法
XML要求所有属性必须带有值,不能使用HTML风格的无值属性(如<script async>)。将其修改为XML兼容的格式:
<script async="async" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script>
这种写法既符合XML规范,也能被浏览器正确识别为HTML的async属性。
2. 用CDATA包裹JavaScript代码
第二个<script>标签内的JS代码可能包含XML敏感字符(即使当前代码没有,也能避免潜在的解析问题),需要用CDATA块包裹,让XML解析器将其视为纯文本:
<script> <![CDATA[ window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX'); ]]> </script>
3. 完整修正后的代码
<script async="async" src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script> <script> <![CDATA[ window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-XXXXXXXXX'); ]]> </script>
内容的提问来源于stack exchange,提问作者Ed S.
相关产品推荐
相关产品推荐

