Inline XML validation against XSD
#there must be reference to xsd file in xml file
<?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="c:\temp\TFSdefaultTasksXML.xsd">
<Task>
<Titles>Create project and TFS structure</Titles>
<Description>Create project and TFS structure, set up builds</Description>
<Effort>1</Effort>
<Priority></Priority>
</Task>
<Task>
<Title>Preliminary Technical design</Title>
<Description></Description>
<Efforty>4</Efforty>
<Priority></Priority>
</Task>
</Tasks>
#TFSdefaultTasksXML.xsd content
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="https://www.w3.org/2001/XMLSchema">
<xs:element name="Tasks">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="Task">
<xs:complexType>
<xs:sequence>
<xs:element name="Title" type="xs:string" />
<xs:element name="Description" type="xs:string" />
<xs:element name="Effort" type="xs:unsignedByte" />
<xs:element name="Priority" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
#Powershell script
$xmlFileName="c:\temp\TFSdefaultTasksXMLinvalid1.xml"
# Validate Schema
#
# Description
# -----------
# Validates an XML file against its inline provided schema reference
#
# Command line arguments
# ----------------------
# xmlFileName: Filename of the XML file to validate
# Check if the provided file exists
if((Test-Path -Path $xmlFileName) -eq $false)
{
Write-Host "XML validation not possible since no XML file found at '$xmlFileName'"
exit 2
}
# Get the file
$XmlFile = Get-Item($xmlFileName)
# Keep count of how many errors there are in the XML file
$errorCount = 0
# Perform the XSD Validation
$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
$readerSettings.add_ValidationEventHandler(
{
# Triggered each time an error is found in the XML file
Write-Host $("`nError found in XML: " + $_.Message + "`n") -ForegroundColor Red
$errorCount++
});
$reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $readerSettings)
while ($reader.Read()) { }
$reader.Close()
# Verify the results of the XSD validation
if($errorCount -gt 0)
{
# XML is NOT valid
exit 1
}
else
{
# XML is valid
exit 0
}