2

I'm fairly new to PowerShell, but have a strong C# background.

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.

The XML looks something like this:

<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:

$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.

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.

2 Answers 2

4

you could do something like:

$downloaded.result.case | %{ $_.InputData }`
| select Firstname,Lastname `
| Export-Csv -path foo.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

2 Comments

Very good, but how can I loop over every Case, not hardcode to case[0]? Also, the columns in the .csv file become separated by comma. How can I choose the delimiter?
edited answer to address your first comment Q. As for the second, in PowerShell v2, there is a -delimiter option, but in v1 it requires a hand coded solution
0

XSLT is a (the?) standard way when it comes to transforming XML to something else.

<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="&#10;" />
  </xsl:template>

</xsl:stylesheet>

Some Powershell context: www.hanselman.com: XSLT with Powershell

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.