Change element text with ansible.windows.win_shell

89 views Asked by At

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?

2

There are 2 answers

0
Keren_H On BEST ANSWER

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")
2
Oliver Gaida On

As you know win_shell calls powershell by default. And if you want to call a method with special characters in powershell, you should quote the method call like this:

$myFile.'element-A'.'element-B' = 'TEXT'

this should work.