none
How to update an Xml Element value using PowerShell

    Question

  • I've been tryign to get this to work. Without any luck.

    Given the following Xml:
    <data>
      <variable name="MPS">
        <row>
          <column>RPS</column>
          <column>500</column>
        </row>
      </variable>
    </data>

    How would I update the second "column" value of 500?

    #$xml = New-Object XML
    #$xml.Load("<XmlFile>")

    $xml.data.variable.row.column  -> returns MPS and 500 as expected
    $xml.data.variable.row.column[1] -> returns 500 as expected
    $xml.data.variable.row.column[1] = $Variable ->  does not work

     

    Thanks   :)

    TR

    Thursday, July 29, 2010 1:05 AM

Answers

  • $variable = Get-Random

    [xml]$xml = Get-Content D:\test.xml
    $xml.data.variable.row.ChildNodes.Item(1)."#text" = "$variable"
    $xml.Save('D:\test.xml')
    Shay Levy [MVP]
    http://blogs.microsoft.co.il/blogs/ScriptFanatic
    PowerShell Toolbar
    • Proposed as answer by BSonPoshModerator Thursday, July 29, 2010 1:52 PM
    • Marked as answer by TR-FS Thursday, July 29, 2010 2:06 PM
    Thursday, July 29, 2010 8:56 AM
  • With a little bit of an XPath magic, you can do the following:

    $x = Select-Xml -Path c:\test.xml -XPath '//column[last()]'

    $x.Node.'#text' = "foo"

    $x.Node.OwnerDocument.Save($x.Path)



    Aleksandar Nikolić http://powershellers.blogspot.com http://twitter.com/alexandair
    • Marked as answer by TR-FS Thursday, July 29, 2010 2:06 PM
    Thursday, July 29, 2010 12:53 PM

All replies