0

I am processing the XML result of a REST API call. I need to convert it to CSV. Based on this answer I could create a working example. However, this solution requires an XML Input file. A more elegant solution for me would be to be able to directly work with the XML result from the web request instead of having to store it first on my hard disk.

Hence, my question is: Is it possible to use the XSLT.Transform() function in Powershell with an XML object/variable instead of a XML file?

I already tried to pass the variable containing the XML to the function, but this yields an error.

My code looks like this:

    $xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
    $xslt.Load("stylesheet.xslt");
    $xslt.Transform($xmlResponse, "test.csv"); #$xmlResponse is of type XmlDocument

The execution of this code leads to a FileNotFoundException, because Powershell tries to resolve the variable $xmlResponse to a file path.

1 Answer 1

2

PowerShell picks the wrong overload because your second argument is a string - and no overloads that accept an IXPathNavigable object (like an XmlDocument for example) takes a string argument as its second parameter.

Create an XmlWriter instance and pass that instead:

try {
  # Create a writer
  $settings = New-Object System.Xml.XmlWriterSettings
  $settings.ConformanceLevel = 'Auto'
  $writer = [System.Xml.XmlWriter]::Create("$PWD\test.csv", $settings)

  # Create your transform
  $xslt = New-Object System.Xml.Xsl.XslCompiledTransform
  $xslt.Load("$PWD\stylesheet.xslt")

  # Pass the writer as the second argument
  $xslt.Transform($xmlResponse, $writer)
}
finally{
  # Dispose of writer to close file handle
  if($writer){
    $writer.Dispose()
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think you need $writer = System.Xml.XmlWriter.Create("test.csv", $xslt.OutputSettings) as XmlWriter has no constructor and as it is likely that the XSLT defines the needed/wanted "settings" using xsl:output. Or don't use an XmlWriter and pass a Stream like a FileStream to the Transform method, I think for that you need to use one of the three argument overloads where you would use null for the second and then the Stream as the third.

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.