Although Mark was faster, I will post this, since it is a bit different - it does not require loading XmlDocument again into stream and it has a full working example:
XmlDocument xml = new XmlDocument();
xml.LoadXml(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<shiporder orderid=""889923"">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
</shiporder>");
xml.Schemas.Add(null, "schema.xsd");
xml.Validate((sender, args) =>
{
switch (args.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("XML is invalid: {0}", args.Exception);
break;
case XmlSeverityType.Warning:
// handle warning
;
break;
}
});
schema.xsd
has the following content:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
You can test validation, by making your xml invalid, e.g. removing element <orderperson>
.
Obviously, you don't need to load XmlDocument, since you already have it and path to your schema must be adapted.