Search code examples
xmlpowershell

Can't change value of nodes with same name


Here is my XML file example :

<?xml version="1.0" encoding="ISO-8859-1"?>
<sc>
    <fluxs>
        <flux>
            <cible>
                <id>0</id>
            </cible>
        </flux>
        <flux>
            <cible>
                <id>1</id>
            </cible>
        </flux>
        <flux>
            <cible>
                <id>2</id>
                <wsdl_url>a</wsdl_url>
                <wsdl_url>b</wsdl_url>
            </cible>
        </flux>
    </fluxs>
</sc>

I want to change the value of nodes "wsdl_url"

I tried this :

$xml = [xml](get-content "c:\mme.xml")

# This works
write-host "Before" $xml.sc.fluxs.flux[2].cible.id
$xml.sc.fluxs.flux[2].cible.id = "Other"
write-host "After" $xml.sc.fluxs.flux[2].cible.id

# This does not work
write-host "Before" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]
$xml.sc.fluxs.flux[2].cible.wsdl_url[0] = "AA"
write-host "After" $xml.sc.fluxs.flux[2].cible.wsdl_url[0]

In the first part, after having change que value of the id node, I get the new value ("Other"). In the second part, nothing change. Whats's wrong ?


Solution

  • As stated in comments, you can use SelectNodes method to get all wsdl_url nodes and from there is up to you what values would you like to use for each one of them. i.e. the below updates both existing nodes by index:

    $nodes = $xml.SelectNodes('//cible/wsdl_url')
    $nodes[0].'#text' = 'hello'
    $nodes[1].'#text' = 'world'
    $xml.Save('path\to\new.xml')
    

    Then the updated XML would look like this:

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <sc>
      <fluxs>
        <flux>
          <cible>
            <id>0</id>
          </cible>
        </flux>
        <flux>
          <cible>
            <id>1</id>
          </cible>
        </flux>
        <flux>
          <cible>
            <id>2</id>
            <wsdl_url>hello</wsdl_url>
            <wsdl_url>world</wsdl_url>
          </cible>
        </flux>
      </fluxs>
    </sc>