首页 > 解决方案 > 在 Powershell 中过滤 XML 数据并以相同的 XML 格式保存到目标文件夹

问题描述

我有一个包含不同国家数据的 XML 文件。我想使用 PowerShell 加载 XML 文件,过滤数据以仅显示英国的数据,然后将结果保存到新的 XML 文件中。我能够加载数据,过滤它但不能保存。过滤数据后,前 2 个节点(数据集和数据)在目标变量中不可见。

我尝试使用 Get-Content 加载文件,使用 "$xml.dataset.data | Where {$_.country.startsWith("UK")}" 过滤数据,然后使用 ".save" 保存结果。

下面是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<dataset>
    <data>
        <Name>Test1</Name>
        <Description>First test in the set</Description>
        <FilePath4>C:\Application\Apple.txt</FilePath4>
        <country>UK</country>
        <FilePath7>C:\Test\Orange.txt</FilePath7>
    </data>
    <data>
        <Name>Test1</Name>
        <Description>Third test in the set</Description>
        <FilePath4>C:\Application\Apple.txt</FilePath4>
        <country>ROI</country>
        <FilePath7>C:\Test\Orange.txt</FilePath7>
    </data>
</dataset>

数据加载: $xml = [System.Xml.XmlDocument](Get-Content C:\Users\HybridPC-40\Desktop\Sample.xml)

数据过滤器: $xml1 = $xml.dataset.data | Where {$_.country.startsWith("UK")}

结果: $xml1 给出

Name        : Test1
Description : First test in the set
FilePath4   : C:\Application\Apple.txt
country     : UK
FilePath7   : C:\Test\Orange.txt

保存: $xml1.save("C:\Users\HybridPC-40\Desktop\Test.xml") 给出以下错误

Method invocation failed because [System.Xml.XmlElement] does not contain a method named 'save'.
At line:1 char:1
+ $xml1.save("C:\Users\HybridPC-40\Desktop\Test.xml")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (save:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

预期结果应该是包含以下数据的新 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<dataset>
    <data>
        <Name>Test1</Name>
        <Description>First test in the set</Description>
        <FilePath4>C:\Application\Apple.txt</FilePath4>
        <country>UK</country>
        <FilePath7>C:\Test\Orange.txt</FilePath7>
    </data>
</dataset>

标签: powershell

解决方案


#creates a record of all or part of a PowerShell session to a text file. 
#The transcript includes all command that the user types and all output that appears on the console.
Start-Transcript -Path "$PSScriptRoot\Log\$($($MyInvocation.MyCommand.Name).TrimEnd("ps1"))log"


$XmlPath = "$PSScriptRoot\Sample.xml"
# same too below ..
#$XmlPath = Join-Path -Path $PSScriptRoot -ChildPath "Sample.xml"

$SavedNewXml = "$PSScriptRoot\Test.xml"


$xml = [xml](Get-Content $XmlPath)
#$xml = [System.Xml.XmlDocument](Get-Content $XmlPath)

$xml1 = $xml.dataset.data | Where {$_.country.startsWith("UK")}


$xml1 | ForEach-Object {
    Write-host "Writing to $SavedNewXml  ..."
    $_ | Out-File -FilePath $SavedNewXml
}

#stops a transcript that was started by the Start-Transcript cmdlet. 
#Alternatively, you can end a session to stop a transcript.
Stop-Transcript

推荐阅读