为什么我使用 Ansbile XML 模块获得带有命名空间的 XML 文档"does not reference a node"?



给定以下XML文档

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>Restricted URLs</web-resource-name>
<url-pattern>/</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
</web-app>

例如,我可以使用Ansiblexml模块来获取文本受限URL

- xml:
path: "simple.xml"
xpath: /web-app/security-constraint/web-resource-collection/web-resource-name
content: text
register: xmlresp
- debug:
var: xmlresp

当我向xml添加名称空间时,例如

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee">
<security-constraint>
<web-resource-collection>
<web-resource-name>Restricted URLs</web-resource-name>
<url-pattern>/</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
</web-app>

并将Ansible YAML代码更改为

- xml:
path: xml-with-namespace.xml"
xpath: /x:web-app/security-constraint/web-resource-collection/web-resource-name
content: text
namespaces:
x: "http://xmlns.jcp.org/xml/ns/javaee"
register: xmlresp
- debug:
var: xmlresp

这会产生错误消息

TASK[centros:xml]********************************************************致命:【centos】:失败=>{"更改":false,"消息":"Xpath"/x: web应用程序/安全约束/web资源集合/web资源名称不引用节点"}

为什么会这样?

xpath表达式不正确。每个元素都应该以名称空间/x:web-app/x:security-constraint/x:web-resource-collection/x:web-resource-name为前缀

- xml:
path: xml-with-namespace.xml"
xpath: /x:web-app/x:security-constraint/x:web-resource-collection/x:web-resource-name
content: text
namespaces:
x: "http://xmlns.jcp.org/xml/ns/javaee"
register: xmlresp
- debug:
var: xmlresp

请参阅community.general.xml–管理xml文件或字符串的各个部分--Ansible Documentation

最新更新