如何使用 PowerShell 根据 XSD 验证 XML 文件? [英] How do I use PowerShell to Validate XML files against an XSD?
问题描述
作为我开发的一部分,我希望能够针对单个 XSD 文件验证整个文件夹中的 XML 文件的价值.PowerShell 函数似乎是一个很好的候选者,因为我可以像这样将文件列表通过管道传递给它: dir *.xml |验证-Xml -Schema .\MySchema.xsd
As a part of my development I'd like to be able to validate an entire folder's worth of XML files against a single XSD file. A PowerShell function seems like a good candidate for this as I can then just pipe a list of files to it like so: dir *.xml | Validate-Xml -Schema .\MySchema.xsd
我已经考虑从 验证 Xml 中移植 C# 代码在 C# 问题中引用了 XSD,但我不知道如何在 PowerShell 中添加处理程序.
I've considered porting C# code from the Validating an Xml against Referenced XSD in C# question, but I don't know how to Add handlers in PowerShell.
推荐答案
我写了一个 PowerShell 函数来做到这一点:
I wrote a PowerShell function to do this:
用法:
目录 *.xml |Test-Xml -Schema ".\MySchemaFile.xsd" -Namespace "http://tempuri.org"
dir *.xml | Test-Xml -Schema ".\MySchemaFile.xsd" -Namespace "http://tempuri.org"
代码:
function Test-Xml {
param(
$InputObject = $null,
$Namespace = $null,
$SchemaFile = $null
)
BEGIN {
$failCount = 0
$failureMessages = ""
$fileName = ""
}
PROCESS {
if ($InputObject -and $_) {
throw 'ParameterBinderStrings\AmbiguousParameterSet'
break
} elseif ($InputObject) {
$InputObject
} elseif ($_) {
$fileName = $_.FullName
$readerSettings = New-Object -TypeName System.Xml.XmlReaderSettings
$readerSettings.ValidationType = [System.Xml.ValidationType]::Schema
$readerSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor
[System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation -bor
[System.Xml.Schema.XmlSchemaValidationFlags]::ReportValidationWarnings
$readerSettings.Schemas.Add($Namespace, $SchemaFile) | Out-Null
$readerSettings.add_ValidationEventHandler(
{
$failureMessages = $failureMessages + [System.Environment]::NewLine + $fileName + " - " + $_.Message
$failCount = $failCount + 1
});
$reader = [System.Xml.XmlReader]::Create($_, $readerSettings)
while ($reader.Read()) { }
$reader.Close()
} else {
throw 'ParameterBinderStrings\InputObjectNotBound'
}
}
END {
$failureMessages
"$failCount validation errors were found"
}
}
这篇关于如何使用 PowerShell 根据 XSD 验证 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!