我幾天前才開始學習 Powershell,所以這對我來說是全新的。問題是我需要盡快完成。所以我有 2 個需要集成的檔案 - 一個 .csv 和一個 .xml。我的想法是轉換其中一個,這樣我首先會有 2 個相同格式的檔案。我讀到 .csv 檔案更容易使用,因此決定將 .xml 檔案轉換為 .csv。但是,我嘗試過的一切都失敗了。但我也找不到與我的 .xml 檔案類似的示例。我的檔案看起來像這樣(一些 ID 是空的):
<Objects>
<Object>
<Property Name="id"/>
<Property Name="username">JLOCK0</Property>
<Property Name="phoneType">phone1</Property>
<Property Name="value">346-209-9609</Property>
</Object>
<Object>
<Property Name="id">vjWJem2qcU cxPT2qIvqsw==</Property>
<Property Name="username">CSELWYN1</Property>
<Property Name="phoneType">phone1</Property>
<Property Name="value">562-981-5379</Property>
</Object>
</Objects>
我嘗試過的所有代碼要么只顯示 id、username、phoneType 和 value 而沒有值,要么只顯示值。向上或向下移動節點無濟于事。我最接近的是這個:
[xml]$xml_file = Get-Content ".\phone.xml"
$xml_file.ChildNodes.ChildNodes | ForEach-Object { $_.ChildNodes[1], $_.ChildNodes[0], $_.ChildNodes[2],
$_.ChildNodes[3]}| ConvertTo-Csv | Out-File ".\phone.csv"
但是使用此代碼,我只得到 2 個標題:名稱和 #text。username、id、phoneType、value 顯示在第一列中,它們的值顯示在第二列中。下面的代碼只添加了標題:
[xml]$data = Get-Content ".\phone.xml"
$result = New-Object psobject -Property $props
$result | Add-Member NoteProperty "id" $data.SelectSingleNode("//Property").id
$result | Add-Member NoteProperty "username" $data.SelectSingleNode("//Property").username
$result | Add-Member NoteProperty "phoneType" $data.SelectSingleNode("//Property").phoneType
$result | Add-Member NoteProperty "value" $data.SelectSingleNode("//Property").value
$result | Export-Csv ".\newphone.csv" -Force -Delimiter ';' -Encoding utf8
uj5u.com熱心網友回復:
可能有更好的方法,但現在這應該可以幫助您構建object[]可以在以下情況下轉換為 CSV 的方法:
$result = foreach($i in $xml.Objects.Object)
{
$out = [ordered]@{}
foreach($prop in $i.Property)
{
$out[$prop.Name] = $prop.'#text'
}
[pscustomobject]$out
}
$result:
id username phoneType value
-- -------- --------- -----
JLOCK0 phone1 346-209-9609
vjWJem2qcU cxPT2qIvqsw== CSELWYN1 phone1 562-981-5379
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/390717.html
