【发布时间】:2018-05-12 07:33:00
【问题描述】:
我正在使用找到的代码 here 来执行 XML 验证:
function Test-Xml {
[cmdletbinding()]
param(
[parameter(mandatory=$true)]$InputFile,
$Namespace = $null,
[parameter(mandatory=$true)]$SchemaFile
)
BEGIN {
$failCount = 0
$failureMessages = ""
$fileName = ""
}
PROCESS {
if ($inputfile)
{
write-verbose "input file: $inputfile"
write-verbose "schemafile: $SchemaFile"
$fileName = (resolve-path $inputfile).path
if (-not (test-path $SchemaFile)) {throw "schemafile not found $schemafile"}
$readerSettings = New-Object -TypeName System.Xml.XmlReaderSettings
$readerSettings.ValidationType = [System.Xml.ValidationType]::Schema
$readerSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessIdentityConstraints -bor
[System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation -bor
[System.Xml.Schema.XmlSchemaValidationFlags]::ReportValidationWarnings
$readerSettings.Schemas.Add($Namespace, $SchemaFile) | Out-Null
$readerSettings.add_ValidationEventHandler(
{
try {
$detail = $_.Message
$detail += "`n" + "On Line: $($_.exception.linenumber) Offset: $($_.exception.lineposition)"
} catch {}
$failureMessages += $detail
$failCount = $failCount + 1
});
try {
$reader = [System.Xml.XmlReader]::Create($fileName, $readerSettings)
while ($reader.Read()) { }
}
#handler to ensure we always close the reader sicne it locks files
finally {
$reader.Close()
}
} else {
throw 'no input file'
}
}
它工作正常,当 XML 和 XSD 模式是“真实文件”时,我可以验证 XML 文件。 现在假设两者都存储在 Variables 中:我已经替换了
$reader = [System.Xml.XmlReader]::Create($fileName, $readerSettings)
与
$reader = [System.Xml.XmlReader]::Create((new-Object System.IO.StringReader($String)), $readerSettings)
which DO WORK,但 StringReader 将所有格式正确的 XML 文件“折叠”到一行,因此 任何验证错误总是在行 1。
有没有办法让 [System.Xml.XmlReader] 处理变量而不是文件,同时保留存储在变量中的格式?
非常感谢
【问题讨论】:
-
我仍在积极寻找答案...
标签: .net xml powershell validation xsd