Tôi muốn nhận xét rằng tập lệnh trong câu trả lời được chấp nhận hiện tại không xác thực lỗi về các đơn đặt hàng không chính xác của các phần tử xs:sequence
. Ví dụ: test.xml
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='test.xsd'>
<address>
<street>Baker street 5</street>
<name>Joe Tester</name>
</address>
</addresses>
test.xsd
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name="addresses">
<xs:complexType>
<xs:sequence>
<xs:element ref="address" minOccurs='1' maxOccurs='unbounded'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element ref="name" minOccurs='0' maxOccurs='1'/>
<xs:element ref="street" minOccurs='0' maxOccurs='1'/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="name" type='xs:string'/>
<xs:element name="street" type='xs:string'/>
</xs:schema>
tôi đã viết một phiên bản khác có thể báo cáo lỗi này:
function Test-XmlFile
{
<#
.Synopsis
Validates an xml file against an xml schema file.
.Example
PS> dir *.xml | Test-XmlFile schema.xsd
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string] $SchemaFile,
[Parameter(ValueFromPipeline=$true, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[alias('Fullname')]
[string] $XmlFile,
[scriptblock] $ValidationEventHandler = { Write-Error $args[1].Exception }
)
begin {
$schemaReader = New-Object System.Xml.XmlTextReader $SchemaFile
$schema = [System.Xml.Schema.XmlSchema]::Read($schemaReader, $ValidationEventHandler)
}
process {
$ret = $true
try {
$xml = New-Object System.Xml.XmlDocument
$xml.Schemas.Add($schema) | Out-Null
$xml.Load($XmlFile)
$xml.Validate({
throw ([PsCustomObject] @{
SchemaFile = $SchemaFile
XmlFile = $XmlFile
Exception = $args[1].Exception
})
})
} catch {
Write-Error $_
$ret = $false
}
$ret
}
end {
$schemaReader.Close()
}
}
PS C: \ temp \ phòng thí nghiệm-xml -validation> dir test.xml | Test-XmlFile test.xsd
System.Xml.Schema.XmlSchemaValidationException: The element 'address' has invalid child element 'name'.
...
Tại sao chính xác bạn cần nó là PowerShell chỉ vì bạn đang đọc danh sách tệp từ stdin? –
Tôi muốn có thể dễ dàng tích hợp nó vào tập lệnh tạo tự động. Không muốn phải biên dịch một ứng dụng chỉ để làm điều này. Một kịch bản PowerShell có vẻ giống như một sự phù hợp tự nhiên cho loại điều này. –