You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Ansible community.general.xml模块转义HTML实体?

Ansible XML模块阻止HTML实体转义的解决方案

问题描述

我想用Ansible的community.general.xml模块修改XML文件,期望得到的<Connector>节点内容如下:

<Connector relaxedQueryChars="[]|{}^&#x5c;&#x60;&quot;&lt;&gt;"/>

我编写的Ansible任务代码如下:

- name: "Update relaxedQueryChars"
  community.general.xml:
    path: "/conf/server.xml"
    xpath: /Server/Service/Connector
    attribute: "relaxedQueryChars"
    value: "[]|{}^&#x5c;&#x60;&quot;&lt;&gt;"

但执行后,所有&都被自动转义成了&amp;,最终得到的XML内容变成了:

<Connector relaxedQueryChars="[]|{}^&amp;#x5c;&amp;#x60;&amp;quot;&amp;lt;&amp;gt;"/>

我试过以下几种写法,都没能阻止转义:

value: '[]|{}^&#x5c;&#x60;&quot;&lt;&gt;'
value: "[]|{}^\&amp;#x5c;\&amp;#x60;\&amp;quot;\&amp;lt;\&amp;gt;"
value: []|{}^\&amp;#x5c;\&amp;#x60;\&amp;quot;\&amp;lt;\&amp;gt;

请问该如何阻止Ansible对HTML实体进行转义?

解决方案

方式1:启用raw参数强制写入原始字符串

community.general.xml模块默认会按照XML规范转义特殊字符,添加raw: yes参数可以让模块直接将传入的value作为原始字符串写入,跳过转义逻辑。修改后的任务代码如下:

- name: "Update relaxedQueryChars"
  community.general.xml:
    path: "/conf/server.xml"
    xpath: /Server/Service/Connector
    attribute: "relaxedQueryChars"
    value: "[]|{}^&#x5c;&#x60;&quot;&lt;&gt;"
    raw: yes

方式2:直接传入实体对应的原始字符

XML里的实体引用最终会被解析为对应的实际字符,你可以直接在value中写入这些字符本身,不需要用实体编码。比如:

  • &#x5c; 对应反斜杠 \
  • &#x60; 对应反引号 `
  • &quot; 对应双引号 "
  • &lt; 对应小于号 <
  • &gt; 对应大于号 >

用单引号包裹value避免YAML解析时转义,修改后的代码如下:

- name: "Update relaxedQueryChars"
  community.general.xml:
    path: "/conf/server.xml"
    xpath: /Server/Service/Connector
    attribute: "relaxedQueryChars"
    value: '[]|{}^\`"<>'

这种方式更符合XML的标准使用逻辑,XML解析器会正常处理这些特殊字符。

内容的提问来源于stack exchange,提问作者shepster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:03:14