本文介绍了如何使用PowerShell 2.0将XML转换为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PowerShell 2.0将以下XML转换为CSV,我可以取出一些数据,但是当尝试遍历XML对象时,我似乎无法仅以某种格式获取数据.请允许我做一张好桌子.

I'm trying to convert the following XML to CSV using PowerShell 2.0, I can get some of the data out but when trying to go through the XML objects I can't seem to get just the data in a format that would allow me to make a good table.

我有类似这样的东西,有多个项目

What I have is something like this, with multiple item's

<root type="array">
  <item type="object">
    <short_version type="string">11</short_version>
    <long_name type="string">Internet Explorer</long_name>
    <api_name type="string">internet explorer</api_name>
    <long_version type="string">11.0.9600.16384.</long_version>
    <latest_stable_version type="string"></latest_stable_version>
    <automation_backend type="string">webdriver</automation_backend>
    <os type="string">Windows 2012 R2</os>
  </item>
  ...
</root>

要么我以Type结尾,要么尝试访问InnerHTML,我只能得到值,但是要得到一个长字符串.

Either I end up with the Type or if I try and access the InnerHTML I get only the values, but in a long string.

我到目前为止:

[xml]$convertMe = Get-Content $jsonTemp
$convertMe.SelectNodes("//item") | % { $_.InnerText }

如何以不错的CSV格式获取此信息?

How can I get this in a nice CSV format like:

推荐答案

这是一个硬编码的长解决方案,但可以. :)尝试:

This is a hard-coded and long solution, but it works. :) Try:

$xml = [xml](Get-Content .\test.xml)

$xml.root.item | Select-Object @(
@{l="short_version";e={$_.short_version."#text"}},
@{l="long_name";e={$_.long_name."#text"}},
@{l="api_name";e={$_.api_name."#text"}},
@{l="long_version";e={$_.long_version."#text"}},
@{l="latest_stable_version";e={$_.latest_stable_version."#text"}},
@{l="automation_backend";e={$_.automation_backend."#text"}},
@{l="os";e={$_.os."#text"}}) |
Export-Csv test.csv -NoTypeInformation

test.csv

"short_version","long_name","api_name","long_version","latest_stable_version","automation_backend","os"
"11","Internet Explorer","internet explorer","11.0.9600.16384.",,"webdriver","Windows 2012 R2"

另一种可能更慢的解决方案:

And alternative and probably slower solution:

$xml = [xml](Get-Content .\test.xml)

#Foreach item
$xml.root.item | ForEach-Object {
    $obj = New-Object psobject
    $_.GetEnumerator() | ForEach-Object {
        #Get all properties/elements and values
        $obj | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.InnerText
    }
    $obj
} |
#Set property order. This also makes sure that all items exports the same properties(which a csv needs)
Select-Object short_version,long_name,api_name,long_version,latest_stable_version,automation_backend,os |
#Export to csv
Export-Csv test.csv -NoTypeInformation

这篇关于如何使用PowerShell 2.0将XML转换为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:54