使用PowerShell将JSON文件内容发送至MSMQ时遇XML生成错误求助
解决PowerShell发送JSON到MSMQ的XML序列化错误
问题原因
你遇到的There was an error generating the XML document错误,是因为Send-MsmqQueue默认会尝试将传入的-Body对象序列化为XML格式。当JSON内容包含XML特殊字符(如&、<、>等)时,XML序列化会失败;而简单字符串不含这类字符,所以能正常发送。
解决方案
方法1:以字节数组形式发送JSON(推荐)
绕过XML序列化,直接发送JSON的字节数组,避免字符冲突:
# 读取JSON文件内容 $jsonContent = Get-Content -Raw -Path "path_to_json" # 转换为UTF8字节数组 $byteContent = [System.Text.Encoding]::UTF8.GetBytes($jsonContent) # 发送到MSMQ队列 Get-MsmqQueue -Name "queue" | Send-MsmqQueue -Body $byteContent -Transactional
接收时还原字符串:
$receivedMessage = Receive-MsmqQueue -Name "queue" -Transactional $jsonString = [System.Text.Encoding]::UTF8.GetString($receivedMessage.Body)
方法2:转义XML特殊字符后发送字符串
如果需要以字符串形式发送,先转义JSON中的XML敏感字符:
$jsonContent = Get-Content -Raw -Path "path_to_json" # 转义XML特殊字符 $escapedJson = [System.Security.SecurityElement]::Escape($jsonContent) # 发送消息 Get-MsmqQueue -Name "queue" | Send-MsmqQueue -Body $escapedJson -Transactional
接收时反转义:
$receivedMessage = Receive-MsmqQueue -Name "queue" -Transactional $originalJson = [System.Security.SecurityElement]::Unescape($receivedMessage.Body)
方法3:用XML文档包裹JSON
将JSON包装在XML节点中,确保序列化正常:
$jsonContent = Get-Content -Raw -Path "path_to_json" # 创建XML文档并包裹转义后的JSON $xmlDoc = New-Object System.Xml.XmlDocument $xmlDoc.LoadXml("<json>$([System.Security.SecurityElement]::Escape($jsonContent))</json>") # 发送XML对象 Get-MsmqQueue -Name "queue" | Send-MsmqQueue -Body $xmlDoc -Transactional
接收时提取JSON:
$receivedMessage = Receive-MsmqQueue -Name "queue" -Transactional $originalJson = [System.Security.SecurityElement]::Unescape($receivedMessage.Body.InnerText)
内容的提问来源于stack exchange,提问作者iaks
相关产品推荐
相关产品推荐

