含&符号的合法XML无法被PowerShell读取的解决求助
解决非标准XML加载失败问题
第三方XML文件内容(无法修改)
C:\Temp\test.xml: <?xml version="1.0" standalone="yes"?> <parameters> <setParameter name="ConnectionString" value="mongodb://svc-dev, connectTimeoutMS=300000&w=majority"/> </parameters>
加载报错信息
执行PowerShell命令加载时出现以下错误:
PS C:\Users\meuser> $xml = [xml](Get-Content "C:\Temp\test.xml") Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "'=' is an unexpected token. The expected token is ';'. Line 3, position 90." At line:1 char:1 + $xml = [xml](Get-Content "C:\Temp\test.xml") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastToXmlDocument
核心需求与现有代码逻辑
需要检查XML是否为空或包含setParameter条目,现有代码如下:
# Check if the XML contains any entries for setParameter if ($xml.parameters.setParameter) { # Check if all the name and value attributes are empty $isEmpty = $xml.parameters.setParameter | ForEach-Object { $_.name -eq "" -and $_.value -eq "" } | Measure-Object -Maximum if ($isEmpty.Maximum -eq 1) { Write-Host "XML RESULTS: All the name and value attributes are empty." #exit 1; } else { Write-Host "XML RESULTS: The XML contains GOOD entries for setParameter." } } else { Write-Host "XML RESULTS: The XML does not contain any entries for setParameter." exit 1; }
注:无法修改原XML文件,后续还需读取键值对并修改后保存为新文件。
解决方案
报错原因是XML中value属性里的&未转义为&,不符合XML规范。由于无法修改原文件,可在加载时先读取文件内容并替换未转义的&,再转换为XML对象:
修改后的加载代码
# 读取文件内容并修复未转义的& $xmlContent = (Get-Content "C:\Temp\test.xml" -Raw) -replace '&(?!amp;|lt;|gt;|quot;|apos;)', '&' # 转换为XML对象 $xml = [xml]$xmlContent
完整验证代码
将上述加载逻辑和原有验证代码整合:
# 加载并修复XML $xmlContent = (Get-Content "C:\Temp\test.xml" -Raw) -replace '&(?!amp;|lt;|gt;|quot;|apos;)', '&' $xml = [xml]$xmlContent # 检查setParameter条目 if ($xml.parameters.setParameter) { $isEmpty = $xml.parameters.setParameter | ForEach-Object { $_.name -eq "" -and $_.value -eq "" } | Measure-Object -Maximum if ($isEmpty.Maximum -eq 1) { Write-Host "XML RESULTS: All the name and value attributes are empty." # exit 1 } else { Write-Host "XML RESULTS: The XML contains GOOD entries for setParameter." } } else { Write-Host "XML RESULTS: The XML does not contain any entries for setParameter." exit 1 }
后续修改保存说明
如果需要修改键值对并保存为新文件,修改XML对象后直接调用Save方法即可,修复后的XML内容符合规范,保存时会自动处理转义:
# 修改示例:修改ConnectionString的value $xml.parameters.setParameter | Where-Object { $_.name -eq "ConnectionString" } | ForEach-Object { $_.value = "mongodb://new-svc, connectTimeoutMS=300000&w=majority" } # 保存为新文件 $xml.Save("C:\Temp\modified_test.xml")
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

