Как использовать оператор if для XML-файла в powershell и как удалить дочерний тег и его содержимое - PullRequest
0 голосов
/ 10 мая 2019

Как использовать оператор if и удалить дочерний тег из вывода этого оператора if в xml-файле, как и из моего кода, я проанализировал все xml-файлы.Теперь я хочу проверить, равен ли sessionType $ name, который является моим входом, а затем удалить данные между тегом int.

1 Ответ

0 голосов
/ 10 мая 2019

Не зная, как выглядит XML-файл, судя по вашему коду, он должен выглядеть примерно так:

<?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>

В этом случае это должно работать:

$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

Редактировать

В случае, если вы НЕ хотите сохранить исходный XML-файл, но перезаписать его обновленным XML-файлом, используйте это:

$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

При использовании с пользовательским вводом Empty результат будет:

<?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>

Надеюсь, что помогает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...