代码之家  ›  专栏  ›  技术社区  ›  Praveen

如何使用Powershell从XML文件中删除特定标记?

  •  2
  • Praveen  · 技术社区  · 10 年前

    从下面的xml片段中,我只想从中删除“ConnectionString”标记 <appSettings> 父标记:

         <configuration>  
            <appSettings>
                <add key="ConnectionString" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
                <add key="ConnectionString1" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
                <add key="ConnectionString2" value=" Data Source=192.168.1.19;Network Library=DBMSSOCN;Initial Catalog=Demo;Persist Security Info=True; User ID=sa;Password=powershell;Application Name=web;Connect Timeout=200; pooling='true'; Max Pool Size=200;"/>
              </appSettings>
        </configuration>
    

    请告诉我如何使用powershell执行此操作?

    2 回复  |  直到 10 年前
        1
  •  3
  •   beatcracker    10 年前

    试试看:

    # Set file path
    $File = '.\config.xml'
    
    # Get file contents as XML
    [xml]$xml = Get-Content $File
    
    # Find node with key="ConnectionString"
    $Remove = $xml.appSettings.configuration.appSettings.add |
                    Where-Object {$_.Key -eq 'ConnectionString'}
    
    # Remove this node from it's parent
    $xml.appSettings.configuration.appSettings.RemoveChild($Remove) | Out-Null
    
    # Save file
    $xml.Save($File)
    
        2
  •  2
  •   vonPryz    10 年前

    删除由节点的父节点完成。首先找到所需的节点,然后通过 ParentNode 所有物然后通过父节点,通过 RemoveChild() 像这样,

    [xml]$doc = cat 'path/to/xml'
    $nodeToRemove = $doc.SelectSingleNode("//add[@key='ConnectionString']")
    $parent = $nodeToRemove.ParentNode
    $parent.RemoveChild($nodeToRemove)
    $doc.Save([console]::out)