I'm fairly new to PowerShell, but have a strong C# background.
我是PowerShell的新手,但拥有强大的C#背景。
The task I'm trying to accomplish is to download some XML, and then save some of the elements from the XML file in a .csv file. I don't need all the elements from the XML, just a few items.
我要完成的任务是下载一些XML,然后将一些XML文件中的元素保存在.csv文件中。我不需要XML中的所有元素,只需要几个项目。
The XML looks something like this:
XML看起来像这样:
<result>
<case>
<InputData>
<Id>1</Id>
<Firstname>John</Firstname>
<Lastname>Smith</Lastname>
<....lots more properties and subnodes I don't need>
</InputData>
</case>
</result>
I've managed to download the XML using something like this:
我已经设法使用以下内容下载XML:
$downloaded = ([Xml](New-Object Net.WebClient).DownloadString("http://url.to.server/file.xml"))
Now I need to extract just a few of the properties from the XML, and export it to CSV file.
现在我需要从XML中提取一些属性,并将其导出到CSV文件。
I understand that I can reach the data with $downloaded.result.case[0].InputData.Firstname, but need some advice on how to extract a few of the properties and save as CSV.
我知道我可以使用$ downloaded.result.case [0] .InputData.Firstname来访问数据,但是需要一些关于如何提取一些属性并保存为CSV的建议。
2 个解决方案
#1
you could do something like:
你可以这样做:
$downloaded.result.case | %{ $_.InputData }`
| select Firstname,Lastname `
| Export-Csv -path foo.csv -NoTypeInformation
#2
XSLT is a (the?) standard way when it comes to transforming XML to something else.
在将XML转换为其他东西时,XSLT是一种(?)标准方法。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="InputData">
<xsl:value-of select="concat('"', Id, '"')" />
<xsl:value-of select="','" />
<xsl:value-of select="concat('"', Firstname, '"')" />
<xsl:value-of select="','" />
<xsl:value-of select="concat('"', Lastname, '"')" />
<xsl:value-of select=" " />
</xsl:template>
</xsl:stylesheet>
Some Powershell context: www.hanselman.com: XSLT with Powershell
一些Powershell背景:www.hanselman.com:带有Powershell的XSLT
#1
you could do something like:
你可以这样做:
$downloaded.result.case | %{ $_.InputData }`
| select Firstname,Lastname `
| Export-Csv -path foo.csv -NoTypeInformation
#2
XSLT is a (the?) standard way when it comes to transforming XML to something else.
在将XML转换为其他东西时,XSLT是一种(?)标准方法。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="InputData">
<xsl:value-of select="concat('"', Id, '"')" />
<xsl:value-of select="','" />
<xsl:value-of select="concat('"', Firstname, '"')" />
<xsl:value-of select="','" />
<xsl:value-of select="concat('"', Lastname, '"')" />
<xsl:value-of select=" " />
</xsl:template>
</xsl:stylesheet>
Some Powershell context: www.hanselman.com: XSLT with Powershell
一些Powershell背景:www.hanselman.com:带有Powershell的XSLT