当您使用 XML 类型帮助程序(即[xml] ...)时,它会验证 xml 以确保在您访问内容之前它的格式正确,但从错误消息看来,您有一些不匹配的标签 -例如:
$text = @(
"<DatiRie_Summary>",
" <node>text</node>",
"</DatiBeniServizi>"
)
$xml = [xml] $text
哪个输出
Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "The 'DatiRie_Summary' start tag on line 1 position 2 does not match the end tag of 'DatiBeniServizi'. Line 3, position 3."
At line:1 char:1
+ $xml = [xml] $text
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToXmlDocument
解决此问题的最佳方法是修复您的 xml 文件,但如果您不控制文件的生成,那么这可能是不可能的。
第二个糟糕的选择可能是改用XmlReader 类。这会“及时”验证 xml,并让您阅读到第一个格式错误的元素。但是,要使用它还有很多工作要做,所以这种权衡可能不值得,而且你仍然最终还是遇到了同样的异常......
$text = @"
<DatiRie_Summary>
<node>mytext</node>
</DatiBeniServizi>
"@
$xmlReader = [System.Xml.XmlReader]::Create((new-object System.IO.StringReader($xmlText)));
while( $xmlReader.Read() )
{
write-host ($xmlReader.NodeType.ToString() + ": '" + $xmlReader.Name + "' = '" + $xmlReader.Value + "'")
}
输出
Element: 'DatiRie_Summary' = ''
Whitespace: '' = '
'
Element: 'node' = ''
Text: '' = 'text'
EndElement: 'node' = ''
Whitespace: '' = '
'
Exception calling "Read" with "0" argument(s): "The 'DatiRie_Summary' start tag on line 1 position 2 does not match the end tag of
'DatiBeniServizi'. Line 3, position 3."
At line:1 char:8
+ while( $xmlReader.Read() )
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : XmlException