How to use if statement for xml file in powershell and how to remove child tag and its content

前端 未结 1 1015
失恋的感觉
失恋的感觉 2021-01-29 15:33

How to use if statement and remove the child tag from output of that if statement in xml file as from my code i parsed all xml files . Now i want to check if sessionType is

相关标签:
1条回答
  • 2021-01-29 15:42

    Without really knowing what the XML file looks like, judging from your code, it should look something like below:

    <?xml version="1.0" encoding="UTF-8"?> 
    <Con> 
        <tar> 
            <tri>
                <int>
                    <ses>Empty</ses>
                    <description>Empty session state</description>
                    <value>0</value>
                </int>
            </tri>
        </tar>
        <tar> 
            <tri>
                <int>
                    <ses>RestrictedRemoteServer</ses>
                    <description>Restricted remote server</description>
                    <value>1</value>
                </int>
            </tri>
        </tar>
        <tar> 
            <tri>
                <int>
                    <ses>Default</ses>
                    <description>Default session state</description>
                    <value>2</value>
                </int>
            </tri>
        </tar>
    </Con>
    

    In that case, this should work:

    $name = Read-Host -Prompt "Enter the name of the sessiontype"
    
    $result = Get-ChildItem -Path 'D:\Testing\TestcasesOutput' -Filter '*.xml' -File -Recurse |   #'# get a collection of xml FileInfo objects
        ForEach-Object {
            $file = $_
            try {
                [xml]$xml = Get-Content -Path $file.FullName -ErrorAction Stop
                # get an array of child nodes where the <ses> nodes contain the wanted sessionType
                $nodes = @($xml.Con.tar.tri.int.ChildNodes | Where-Object { $_.'#text' -eq $name })
                if ($nodes) {
                    # we have found <ses> nodes containing the wanted sessionType 
                    [PSCustomObject]@{
                        'File'        = $file.FullName  
                        'SessionType' = $nodes[0].'#text'
                    }
                    # loop through the $nodes array 
                    $nodes | ForEach-Object {
                        ## DECIDE WHAT TO DO HERE ##
    
                        # remove all the subnodes of the <int> node, leaving an empty node <int></int>
                        $_.ParentNode.RemoveAll()
    
                        # OR: remove the <int> node completely, including all sub nodes
                        # $_.ParentNode.ParentNode.RemoveAll()
    
                        # OR: just remove the <ses>...</ses> subnode within the <int> node
                        # [void]$_.ParentNode.RemoveChild($_)
                    }
    
                    # create a filename for the output by adding 'Updated' to the name
                    $outputfile = Join-Path -Path $file.DirectoryName -ChildPath ('{0}_Updated{1}' -f $file.BaseName, $file.Extension)
                    # save the updated XML file
                    Write-Host "Saving file '$outputfile'"
                    $xml.Save($outputfile)
                }
                else {
                    Write-Host "File '$($file.FullName)' did not contain SessionType $name"
                }
            }
            catch {
                Write-Warning "Bad XML file found: '$($file.FullName)'"
            }
        }
    
    # output on screen
    $result
    
    # or save the results as CSV file somewhere
    # $result | Export-Csv -Path 'PATH TO THE RESULTS CSV FILE' -NoTypeInformation
    

    Edit

    In case you do NOT want to preserve the original XML file, but overwrite it with the updated xml, use this:

    $name = Read-Host -Prompt "Enter the name of the sessiontype"
    
    $result = Get-ChildItem -Path 'D:\Testing\TestcasesOutput' -Filter '*.xml' -File -Recurse |   #'# get a collection of xml FileInfo objects
        ForEach-Object {
            $file = $_.FullName
            try {
                [xml]$xml = Get-Content -Path $file -ErrorAction Stop
                # get an array of child nodes where the <ses> nodes contain the wanted sessionType
                $nodes = @($xml.Con.tar.tri.int.ChildNodes | Where-Object { $_.'#text' -eq $name })
                if ($nodes) {
                    # we have found <ses> nodes containing the wanted sessionType 
                    [PSCustomObject]@{
                        'File'        = $file  
                        'SessionType' = $nodes[0].'#text'
                    }
                    # loop through the $nodes array 
                    $nodes | ForEach-Object {
                        ## DECIDE WHAT TO DO HERE ##
    
                        # remove all the subnodes of the <int> node, leaving an empty node <int></int>
                        $_.ParentNode.RemoveAll()
    
                        # OR: remove the <int> node completely, including all sub nodes
                        # $_.ParentNode.ParentNode.RemoveAll()
    
                        # OR: just remove the <ses>...</ses> subnode within the <int> node
                        # [void]$_.ParentNode.RemoveChild($_)
                    }
    
                    # save the updated XML file
                    Write-Host "Saving file '$file'"
                    $xml.Save($file)
                }
                else {
                    Write-Host "File '$file' did not contain SessionType $name"
                }
            }
            catch {
                Write-Warning "Bad XML file found: '$file'"
            }
        }
    
    # output on screen
    $result
    
    # or save the results as CSV file somewhere
    # $result | Export-Csv -Path 'PATH TO THE RESULTS CSV FILE' -NoTypeInformation
    

    When used with a user input of Empty, the result will be:

    <?xml version="1.0" encoding="UTF-8"?>
    <Con>
      <tar>
        <tri>
          <int>
          </int>
        </tri>
      </tar>
      <tar>
        <tri>
          <int>
            <ses>RestrictedRemoteServer</ses>
            <description>Restricted remote server</description>
            <value>1</value>
          </int>
        </tri>
      </tar>
      <tar>
        <tri>
          <int>
            <ses>Default</ses>
            <description>Default session state</description>
            <value>2</value>
          </int>
        </tri>
      </tar>
    </Con>
    

    Hope that helps

    0 讨论(0)
提交回复
热议问题