Windows Vista Forums

Re: how to change xml values
  1. #1


    Kiron Guest

    Re: how to change xml values

    You can use XPath notation to get the node's attribute and set its new value:

    [xml]$xml = gc c:\data.xml
    $xml.selectSingleNode('//add[@key="TCPport"]').value = '3000'
    $xml.selectSingleNode('//add[@key="tserver"]').value = 'server9'
    $xml.save('c:\data.xml') # <-- full path



    --
    Kiron

      My System SpecsSystem Spec

  2. #2


    Kiron Guest

    Re: how to change xml values

    '//add' is XPath for "select all 'add' child nodes anywhere in the xmlDocument" and '@key' means the 'key' attribute. So '//add[@key="TCPport"]' means select the 'add' node whose 'key' attribute's value is "TCPport".

    If you're interested, this is a good tutorial:
    http://www.w3schools.com/xpath/xpath_syntax.asp

    --
    Kiron

      My System SpecsSystem Spec

  3. #3


    Kiron Guest

    Re: how to change xml values

    In PowerShell xml nodes can be accessed through the dot operator, like object properties. Sometimes there can be more than one node with the same name, there you can use array notation.
    For example, you can get all the 'add' nodes, filter the one whose 'key' attribute's value -eq 'TCPport' and set its 'value' attribute's value to '3000' this way also:

    $xml.configuration.appSettings.add |
    ? {$_.key -eq 'TCPport'} | % {$_.value = '3000'}

    # get-member can help you discover the elements
    $xml | gm -t property

    # the ChildNodes property lists the node's childNodes, if any
    $xml.childNodes | select name
    $xml.configuration.childNodes | select name

    # ...etc.


    I don't know if there is a .NET property/method that will display the element list, hope I'm wrong.
    Something like this gets you a list of the element names:

    [xml]$xml = gc c:\data.xml
    $xml | fc | out-string -str | ? {$_ -match $rgx} |
    % {$h = @{}; $c = 0} {$h."$($rgx.replace($_,'$1'))" = $c++}
    $elements = $h.getEnumerator() | sort {[int]$_.value} |
    ? {$_.name -match '^\w'} | % {$_.name}
    $elements

    --
    Kiron

      My System SpecsSystem Spec

  4. #4


    Kiron Guest

    Re: how to change xml values

    Forgot to include the RegEx...
    [regex]$rgx = '\s+(\S+) =.+'

    --
    Kiron

      My System SpecsSystem Spec

Re: how to change xml values problems?

Similar Threads
Thread Thread Starter Forum Replies Last Post
Lookup values Morphius PowerShell 3 11 Sep 2009
multiline values TPGBrennan PowerShell 2 09 Apr 2009
ram wrong values Bogdan Florian Vista performance & maintenance 1 01 Sep 2008
values PaulR VB Script 2 20 Aug 2008
Tip: CRC and MD5 values for Vista John Barnes Vista General 2 06 Sep 2006