【问题标题】:在 Powershell 中将 xml 转换为 csv 文件
【发布时间】:2022-01-23 07:18:25
【问题描述】:

我几天前才开始学习 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、用户名、phoneType 和不带值的值,要么只显示值。向上或向下移动节点无济于事。我得到的最接近的是:

    [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。用户名、id、phoneType、值显示在第一列,它们的值显示在第二列。 下面的代码只添加了标题:

[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

【问题讨论】:

    标签: xml powershell csv type-conversion


    【解决方案1】:

    可能有更好的方法,但现在这应该可以帮助您构建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
    

    【讨论】:

    • 这可能是最好的——做得很好。
    • @mklement0 谢谢!我认为使用 xml 方法会有更好的方法,但我几乎没有使用它们的经验:P
    • 非常感谢,成功了!
    • @momp 乐于助人,很高兴它成功了!
    猜你喜欢
    • 2020-06-10
    • 2017-09-09
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2015-10-28
    • 2014-11-22
    • 2017-04-18
    相关资源
    最近更新 更多