如何在powershell中对xml文件使用if语句以及如何删除子标签及其内容 [英] How to use if statement for xml file in powershell and how to remove child tag and its content

查看:37
本文介绍了如何在powershell中对xml文件使用if语句以及如何删除子标签及其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 if 语句并从该语句的输出中删除子标记xml 文件中的 if 语句与我的代码一样,我解析了所有 xml 文件.现在我想检查 sessionType 是否等于 $name 这是我的输入然后删除int标签之间的数据.

解决方案

在不真正了解 XML 文件的情况下,从您的代码来看,它应该如下所示:

<块引用>

<int><ses>空</ses><description>空会话状态</description><值>0</值></int></tri></tar><焦油><三><int><ses>RestrictedRemoteServer</ses><description>受限远程服务器</description><值>1</值></int></tri></tar><焦油><三><int><ses>默认</ses><description>默认会话状态</description><值>2</值></int></tri></tar></Con>

在这种情况下,这应该有效:

$name = Read-Host -Prompt "输入会话类型的名称"$result = Get-ChildItem -Path 'D:\Testing\TestcasesOutput' -Filter '*.xml' -File -Recurse |#'# 获取 xml FileInfo 对象的集合ForEach-Object {$文件 = $_尝试 {[xml]$xml = Get-Content -Path $file.FullName -ErrorAction 停止# 获取一个子节点数组,其中 ;节点包含想要的 sessionType$nodes = @($xml.Con.tar.tri.int.ChildNodes | Where-Object { $_.'#text' -eq $name })如果($节点){# 我们找到了<ses>包含所需 sessionType 的节点[PSCustomObject]@{'文件' = $file.FullName'SessionType' = $nodes[0].'#text'}# 遍历 $nodes 数组$nodes |ForEach-Object {##决定在这里做什么### 删除  的所有子节点;节点,留下一个空节点 <int></int>$_.ParentNode.RemoveAll()# 或:删除 <int>完全节点,包括所有子节点# $_.ParentNode.ParentNode.RemoveAll()# 或:只需删除 <ses>...</ses> 中的子节点节点# [void]$_.ParentNode.RemoveChild($_)}# 通过在名称中添加已更新"来为输出创建一个文件名$outputfile = Join-Path -Path $file.DirectoryName -ChildPath ('{0}_Updated{1}' -f $file.BaseName, $file.Extension)# 保存更新的 XML 文件写主机保存文件‘$outputfile’"$xml.Save($outputfile)}别的 {写入主机文件 '$($file.FullName)' 不包含 SessionType $name"}}抓住 {写警告发现错误的 XML 文件:'$($file.FullName)'"}}# 屏幕输出$结果# 或将结果另存为 CSV 文件# $result |Export-Csv -Path 'PATH TO THE RESULTS CSV FILE' -NoTypeInformation

<小时>

编辑

如果您不想想要保留原始 XML 文件,而是用更新的 xml 覆盖它,请使用:

$name = Read-Host -Prompt "输入会话类型的名称"$result = Get-ChildItem -Path 'D:\Testing\TestcasesOutput' -Filter '*.xml' -File -Recurse |#'# 获取 xml FileInfo 对象的集合ForEach-Object {$file = $_.FullName尝试 {[xml]$xml = Get-Content -Path $file -ErrorAction 停止# 获取一个子节点数组,其中 ;节点包含想要的 sessionType$nodes = @($xml.Con.tar.tri.int.ChildNodes | Where-Object { $_.'#text' -eq $name })如果($节点){# 我们找到了<ses>包含所需 sessionType 的节点[PSCustomObject]@{'文件' = $文件'SessionType' = $nodes[0].'#text'}# 遍历 $nodes 数组$nodes |ForEach-Object {##决定在这里做什么### 删除  的所有子节点;节点,留下一个空节点 <int></int>$_.ParentNode.RemoveAll()# 或:删除 <int>完全节点,包括所有子节点# $_.ParentNode.ParentNode.RemoveAll()# 或:只需删除 <ses>...</ses> 中的子节点节点# [void]$_.ParentNode.RemoveChild($_)}# 保存更新的 XML 文件写主机保存文件‘$file’"$xml.Save($file)}别的 {写主机文件‘$file’不包含SessionType $name"}}抓住 {写警告发现错误的 XML 文件:‘$file’"}}# 屏幕输出$结果# 或将结果另存为 CSV 文件# $result |Export-Csv -Path 'PATH TO THE RESULTS CSV FILE' -NoTypeInformation

<小时>

当与用户输入 Empty 一起使用时,结果将是:

<块引用>

<int></int></tri></tar><焦油><三><int><ses>RestrictedRemoteServer</ses><description>受限远程服务器</description><值>1</值></int></tri></tar><焦油><三><int><ses>默认</ses><description>默认会话状态</description><值>2</值></int></tri></tar></Con>

希望有帮助

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 equal to $name which is my input then remove the data between int tag.

解决方案

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

这篇关于如何在powershell中对xml文件使用if语句以及如何删除子标签及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆