【问题标题】:How to remove particular tag from XML file using Powershell?如何使用 Powershell 从 XML 文件中删除特定标签?
【发布时间】:2015-03-26 12:31:17
【问题描述】:

从下面的 xml sn-p 我想只删除“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 执行此操作?

【问题讨论】:

    标签: xml powershell iis powershell-ise cmdlet


    【解决方案1】:

    试试这个:

    # 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)
    

    【讨论】:

    • 感谢它为我工作。从 appSettings 标记中删除连接字符串后。我仍然必须从 appSettings 标记中选择 30 多个标记,并且需要将选定的标记复制到另一个 xml 文件。请让我知道该怎么做?标签具有键值,例如
    【解决方案2】:

    删除由节点的父节点完成。首先找到所需的节点,您将通过ParentNode 属性获得其父节点。然后通过父节点,通过RemoveChild() 删除子节点。像这样,

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

    【讨论】:

    • SelectSingleNode 在 powershell 2.0 中不起作用?所以我像这样使用过 $doc .configuration.appSettings.add | Where-Object {$_.Key -eq 'ConnectionString'}。保存到文件时出现以下错误:无法将值“System.Xml.XmlElement”转换为类型“System.Xml.XmlDocument”。错误:“根级别的数据无效。第 1 行,位置 1。”在第 11 行 char:32 + $parent = [xml] $nodeToRemove。
    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 2019-10-27
    • 1970-01-01
    • 2020-09-02
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多