Search code examples
xmlansiblewin-shell

Change element text with ansible.windows.win_shell


I try to change an element text, using ansible.windows.win_shell.

This is the XML I have:

<element-A>
    <element-B />
</element-A>

and this is the XML I would like to have:

<element-A>
    <element-B> TEXT </element-B>
</element-A>

The win_shell I tried to run:

- name: some-name
  win_shell: |
    [xml]$myFile = Get-Content "C:\MyFile.xml"
    $myFile.element-A.element-B = 'TEXT'
    $myFile.Save("C:\MyFile.xml")

The error I get:

"The property 'element-B' cannot be found on this object. Verify that the property exists and can be set."

Can someone help?


Solution

  • Using SelectSingleNode solved the problem for me:

       - name: some-name
          win_shell: |
            [xml]$myFile = Get-Content "C:\MyFile.xml"
            $myFile.SelectSingleNode("//element-A/element-B").InnerText = "TEXT"
            $myFile.Save("C:\MyFile.xml")