gpt4 book ai didi

xml - 在Powershell(Spacewalk)中将XML转换为CSV

转载 作者:行者123 更新时间:2023-12-02 23:33:37 25 4
gpt4 key购买 nike

我对PowerShell的经验很少,需要将以下摘录从XML文件转换为CSV格式。有人可以帮我转换此代码吗?

这是我坚持之前所能做的事情的延伸。

$xdoc = new-object System.Xml.XmlDocument
$xdoc.Load("$getUnscheduledErrataPath")

$members = $xdoc.SelectSingleNode("//struct").member.name

$xmldata = ((Select-Xml -Path "$getUnscheduledErrataPath" -XPath "//struct") | ForEach-Object { $_.Node })

XML输入:
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value>
<array>
<data>
<value>
<struct>
<member><name>id</name><value><i4>26660</i4></value></member>
<member><name>date</name><value><string>9/4/18</string></value></member>
<member><name>advisory_synopsis</name><value><string> ovmd xenstoreprovider bug fix update</string></value></member>
<member><name>advisory_name</name><value><string>ELBA-2018-4206</string></value></member>
<member><name>advisory_type</name><value><string>Bug Fix Advisory</string></value></member>
</struct>
</value>
<value>
<struct>
<member><name>id</name><value><i4>18094</i4></value></member>
<member><name>date</name><value><string>1/29/19</string></value></member>
<member><name>advisory_synopsis</name><value><string> module-init-tools bug fix update</string></value></member>
<member><name>advisory_name</name><value><string>ELBA-2019-4527</string></value></member>
<member><name>advisory_type</name><value><string>Bug Fix Advisory</string></value></member>
</struct>
</value>
</data>
</array>
</value>
</param>
</params>
</methodResponse>

最佳答案

为了创建我们可以有意义地转换为CSV的内容,我将采用以下方法(伪代码):

foreach <struct>
{
foreach <member>
{
collect <name>, parse <value>
}

Convert <member> results to object
}

在PowerShell中,看起来像这样:
$objects = foreach($struct in $xdoc.SelectNodes('//struct')){
# Create a dictionary to store the <member> values
$properties = [ordered]@{}

# Iterate over <member> child nodes
foreach($member in $struct.SelectNodes('member')){
# <name> is easy
$name = $member.SelectSingleNode('name').innerText

# for <value> nodes I'm grabbing all ChildNodes and just select the first 1
$valueNode = $member.SelectSingleNode('value').ChildNodes |Select -First 1

# Here you could make decisions based on `$valueNode.Name`,
# like converting <i4> values to an [int] for example
#
# But since the purpose is to export to csv, that doesn't make much sense here

# Add extracted values to dictionary
$properties[$name] = $valueNode.innerText
}

# create object based on extracted properties
[pscustomobject]$properties
}

# Export resulting objects to CSV
$objects |Export-Csv -Path C:\path\to\output.csv -NoTypeInformation

关于xml - 在Powershell(Spacewalk)中将XML转换为CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60850911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com