Search code examples
xmlpowershellxslt

Applying XSL to XML with PowerShell : Exception calling "Transform"


I'm trying to clean XML Files with an XSL Transformation. When I'm applying my XSL directly to my XML File, it works fine. But now I want to clean every XML File I have in a directory. I've tried to create a PowerShell script, to load and transform XML Files.

Here is my code :

$dir = "C:\MyDirectory"
$XSLFileName = "XSLTFile.xsl"
$XSLFileInput = $dir + $XSLFileName

$XMLFileName = "Input.xml"
$XMLInputFile = $dir + $XMLFileName
$OutputFileName = "Output.xml"
$XMLOutputFile = $dir + $OutputFileName

cd $dir 

$XSLInputElement = New-Object System.Xml.Xsl.XslCompiledTransform;
$XSLInputElement.Load($XSLFileInput)

$XMLInputDoc = Get-Content -Path $XMLInputFile

$reader = [System.Xml.XmlReader]::Create($XMLInputFile)
$writer = [System.Xml.XmlTextWriter]::Create($XMLOutputFile)

$XSLInputElement.Transform($XMLInputDoc, $writer)

I've been threw some docs and SO subjects to find how to use the Transform() method, but I haven't found how to deal with this error :

Exception calling "Transform" with "2" argument(s): "Caractères non conformes dans le chemin d'accès."
At C:\ScirptsDirs\StackOverFlowTransformExample.ps1:20 char:1
+ $XSLInputElement.Transform($XMLInputDoc, $writter)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException

Note : "Caractères non conformes dans le chemin d'accès." means : Invalid symbol found in the access path.

What I want to do is to clean my XML File, and to create an other XML File but with the XSL Transformation applied to it.

EDIT : I've also tried this way, as Martin said :

$XSLInputElement.Transform($XMLInputFile, $XMLOutputFile)

But this time, I have thee following error :

Exception calling "Transform" with "2" argument(s): "Execution of the 'document()' function was prohibited. Use the XsltSettings.EnableDocumentFunction property to enable it. An error occurred at  D:\MyDirectory\XSLTFile.xsl(220,3)."
At C:\ScirptsDirs\StackOverFlowTransformExample.ps1:20 char:1
+ $XSLInputElement.Transform($XMLInputFile, $XMLOutputFile)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : XslTransformException

Solution

  • If you have the input and output file name respectively path as a string then simply use $XSLInputElement.Transform($XMLInputFile, $XMLOutputFile).