How to change the value of XML Element attribute using PowerShell?

前端 未结 3 661
南旧
南旧 2020-12-11 00:05

I am trying to access and change the particular attribute from XML tag

XML:


  
    <         


        
相关标签:
3条回答
  • 2020-12-11 00:14

    Try the following:

    $nodes = $xml.SelectNodes("/office/staff");
    foreach($node in $nodes) {
        $node.SetAttribute("branch", "New York");
    }
    

    This will iterate through all nodes returned by SelectNodes() and modify each one.

    0 讨论(0)
  • 2020-12-11 00:17

    You can access the attributes directly in the [xml] object like this:

    # C:\temp> $xml = [xml](Get-Content C:\FE6Work.xml)
    # C:\temp> $xml.office.staff
    
    branch                   Type                           employee                                                             
    ------                   ----                           --------                                                             
    Hanover                  sales                          {Tobias Weltner, Cofi Heidecke}                                      
    London                   Technology                     {XXXX, Cofi}                                                         
    
    # C:\temp> $xml.office.staff | foreach{$_.branch = "New York"}
    # C:\temp> $xml.office.staff
    
    branch                   Type                           employee                                                             
    ------                   ----                           --------                                                             
    New York                 sales                          {Tobias Weltner, Cofi Heidecke}                                      
    New York                 Technology                     {XXXX, Cofi}                                                         
    
    0 讨论(0)
  • 2020-12-11 00:25

    if we are taking attribute from console and changing its value ?

    $path=Read-Host -Prompt 'Enter path of xml file'
    [xml]$xmldata = get-content "$path"
    
    $tag = Read-Host -Prompt 'Enter tag'
    $value = Read-Host -Prompt 'Enter value'
    $xmldata.InstallConfig.$tag="$value"
    $xmldata.Save($path)
    
    0 讨论(0)
提交回复
热议问题