I am using this code to load XML that has the potential for errors (human edited).
$xmlReaderSettings = [System.Xml.XmlReaderSettings]::new()
$xmlReaderSettings.CloseInput = $True
$xmlReaderSettings.IgnoreWhitespace = $True
$xmlReaderSettings.IgnoreComments = $True
try {
$xmlReader = [System.Xml.XmlReader]::Create("$xmlPath\$file", $xmlReaderSettings)
$tempXml = [System.Xml.XmlDocument]::new()
$tempXml.Load($xmlReader)
} catch [System.Management.Automation.ItemNotFoundException] {
Write-PxLog "*_Cannot find '$($file.Name)'"
} catch {
Write-PxLog "*_Malformed XML in '$($file.Name)'"
Write-PxLog "*_$($PSItem.Exception.Message)"
$proceed = $false
} finally {
$xmlReader.Close()
}
This seems to catch all errors except errors related to comments. Specifically, Autodesk uses arguments like --trigger_point system
for their uninstalls, and I have that in the XML. If that XML get's commented there is a problem, because a comment can't contain --
. Unfortunately, the code above completely misses that error. I can use
if ($tempXml.DocumentElement) {
# continue with validating loaded XML
} else {
# report generic error here
}
I would prefer to provide a more detailed error message, ideally with line numbers. But I would have expected $xmlReaderSettings.IgnoreComments = $True
would have solved the issue, as the comments get ignored, and the error is in the comments. If I output the XML again, the comments are missing, but it would seem that IgnoreComments
really means IgnoreWellFormedComments
, and I have to deal with the issue some other way?
Is there a way to actually ignore malformed comments? And if not, why am I not seeing an exception caught? And is there a better answer than "Something happened and it might be a problem in a comment but I can't tell you where, thanks Microsoft." ?