如何在PowerShell的XSLT转换中输出xsl:message?
Got it, I've run into this exact issue before! The problem is that by default, the .NET XslCompiledTransform class doesn't surface xsl:message output automatically—you need to subscribe to its XsltMessageEncountered event to capture and display those messages. Here's how to modify your TransformXML function to make this work:
Updated TransformXML Function with xsl:message Support
function TransformXML { param( [Parameter(Mandatory=$true)] [string]$InputPath, [Parameter(Mandatory=$true)] [string]$XsltPath, [Parameter(Mandatory=$true)] [string]$OutputPath ) # Initialize the XSLT transformation engine $xslt = New-Object System.Xml.Xsl.XslCompiledTransform # Subscribe to the message event to capture and display xsl:message content $eventSubscription = Register-ObjectEvent -InputObject $xslt -EventName XsltMessageEncountered -Action { # Customize this line to change how messages are output (console, file, etc.) Write-Host "* XSLT Message: $($EventArgs.Message)" -ForegroundColor Cyan } try { # Load the stylesheet and execute the transformation $xslt.Load($XsltPath) $xslt.Transform($InputPath, $OutputPath) } finally { # Clean up the event subscription to avoid memory leaks Unregister-Event -SubscriptionId $eventSubscription.Id } }
How It Works
- Event Subscription: The
Register-ObjectEventcmdlet hooks into theXsltMessageEncounteredevent fired byXslCompiledTransformevery time anxsl:messageis processed in your stylesheet. - Action Block: The
-Actionscript block defines what to do with the message—here we print it to the console with a colored prefix for visibility. You can easily modify this to write to a log file, send to a monitoring tool, etc. - Cleanup: The
finallyblock ensures we unregister the event even if the transformation fails, preventing lingering subscriptions that can cause memory leaks in long-running PowerShell sessions.
Test with Your Sample XSLT
If you run the function with your stylesheet (and any valid input XML file), you'll see the message appear in the console:
TransformXML -InputPath "your-input.xml" -XsltPath "your-stylesheet.xsl" -OutputPath "output.xml"
Expected output:
- XSLT Message: hello
The transformed XML will still be saved to output.xml as usual.
Customization Tip
To route messages to a log file instead of the console, update the action block like this:
$eventSubscription = Register-ObjectEvent -InputObject $xslt -EventName XsltMessageEncountered -Action { $logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - XSLT Message: $($EventArgs.Message)" Add-Content -Path "xslt-log.txt" -Value $logEntry }
内容的提问来源于stack exchange,提问作者orange-lily
相关产品推荐
相关产品推荐

