使用Ansible编辑XML无法生成预期格式的问题求助
Ansible编辑XML添加元素问题解决
问题场景
尝试用Ansible编辑XML添加新元素时遇到两个问题:
- 第一段代码生成格式错误的
<Testattribute>节点 - 第二段代码添加子节点的操作完全没生效
第一段尝试代码
- name: Add a element to the 'business' element community.general.xml: path: /tmp/temp.xml xpath: /x:Activity/x:ActivityDetails/x:listOfActivityAttribute/x:Testattribute namespaces: x: "http://test.com/xsd/crm/v1/Activity/ManageInternalCustomerChange" attribute: validatedon value: 1976-08-05
第一段代码实际输出(格式错误部分)
<Testattribute <validatedon=\"1976-08-05\"/>
第二段尝试代码
- name: Add a element to the 'business' element community.general.xml: path: /tmp/temp.xml xpath: /x:Activity/x:ActivityDetails/x:listOfActivityAttribute/x:Testattribute namespaces: x: "http://capabilities.nat.bt.com/xsd/crm/v1/Activity/ManageInternalCustomerChange" add_children: - validatedon: 1976-08-05
预期XML输出
<ActivityDetails> <activityId>bcb45088-21aa-4ec4-b453-5f08af0fc612</activityId> <activityType>ServiceIdRecordUpdate</activityType> <activityStartDate>%DateTime%</activityStartDate> <listOfActivityAttribute> <activityAttribute> <name>CustomerId</name> <value>%CustomerId%</value> </activityAttribute> <activityAttribute> <name>AssetInstanceId</name> <value>%AssetInstanceId%</value> </activityAttribute> <activityAttribute> <name>ServiceId</name> <value>%ServiceId%</value> </activityAttribute> <activityAttribute> <name>SupplierServiceId</name> <value>%SupplierServiceId%</value> </activityAttribute> <Testattribute> <name>validatedon</name> <value>1976-08-05</value> </Testattribute> </listOfActivityAttribute> </ActivityDetails> </Activity>
问题原因分析
第一段代码问题:
- 使用了
attribute参数,这个参数是给指定节点添加属性的,而你需要的是在<Testattribute>下添加子节点<name>和<value>,方向完全错了。 - 原XML中不存在
<Testattribute>节点,直接用这个xpath定位会导致Ansible生成的节点格式异常。
- 使用了
第二段代码问题:
- xpath指向的
<Testattribute>节点原本不存在,add_children找不到目标节点,所以操作无效果。 - 你要的是
<name>和<value>子节点,而不是直接添加<validatedon>节点。
- xpath指向的
正确解决方案
直接在已存在的<listOfActivityAttribute>节点下创建<Testattribute>并嵌套所需的子节点,一次操作完成:
- name: Add Testattribute with name and value children community.general.xml: path: /tmp/temp.xml xpath: /x:Activity/x:ActivityDetails/x:listOfActivityAttribute namespaces: x: "http://test.com/xsd/crm/v1/Activity/ManageInternalCustomerChange" add_children: - Testattribute: - name: validatedon - value: 1976-08-05
说明
- xpath定位到已存在的
<listOfActivityAttribute>节点,避免找不到目标的问题。 - 通过
add_children直接构建<Testattribute>节点及其子节点结构,完全匹配预期格式。 - 注意统一命名空间,第二段代码里的命名空间和第一段不一致,要改成正确的那个。
内容的提问来源于stack exchange,提问作者Hari3090
相关产品推荐
相关产品推荐

