title: Validating XML with XSD
body: <p>I'm running into real difficulties validating XML with <a href="http://en.wikipedia.org/wiki/XML_Schema_%28W3C%29" rel="nofollow noreferrer">XSD</a>. I should prefix all of this and state up front, I'm new to XSD and validation, so I'm not sure if it's a code issue or an XML issue. I've been to XML API hell and back with the bajillion different options and think that I've found what would be the ideal strategy for validating XML with XSD. Note, my XML and XSD are coming from a database, so I don't need to read anything from disk.</p>
  
  <p>I've narrowed my problem down into a simple sample <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> application. It has a textbox for XSD (txtXsd), a textbox for XML (txtXml), a textbox for the result (txtResult), and a button to start the validation (btnValidate).</p>
  
  <p>I'm using a sample XSD file from Microsoft,</p>
  
  <pre><code>&lt;xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema"&gt;
      &lt;xsd:element name="title" type="xsd:string" /&gt;
      &lt;xsd:element name="comment" type="xsd:string" /&gt;
      &lt;xsd:element name="author" type="authorName"/&gt;
      &lt;xsd:complexType name="authorName"&gt;
          &lt;xsd:sequence&gt;
              &lt;xsd:element name="first-name" type="xsd:string" /&gt;
              &lt;xsd:element name="last-name" type="xsd:string" /&gt;
          &lt;/xsd:sequence&gt;
      &lt;/xsd:complexType&gt;
  &lt;/xsd:schema&gt;
  </code></pre>
  
  <p>I'm using the following code in my application.</p>
  
  <pre><code>private void btnValidate_Click (object sender, EventArgs e)
  {
      try
      {
          XmlTextReader reader = new XmlTextReader(txtXsd.Text, XmlNodeType.Document, new XmlParserContext(null, null, String.Empty, XmlSpace.None));
          XmlSchema schema = XmlSchema.Read(reader, null);
          XmlSchemaSet schemas = new XmlSchemaSet();
          schemas.Add(schema);
  
          XDocument doc = XDocument.Parse(txtXml.Text);
          doc.Validate(schemas, ValidateSchema);
      }
      catch (Exception exception)
      {
          txtResult.Text += exception.Message + Environment.NewLine;
      }
  }
  
  private void ValidateSchema (Object sender, ValidationEventArgs e)
  {
      txtResult.Text += e.Message + Environment.NewLine;
  }
  </code></pre>
  
  <p>As a test, I put in valid XML, but what I think should not conform to the XSD above.</p>
  
  <pre><code>&lt;xml&gt;
      &lt;bogusNode&gt;blah&lt;/bogusNode&gt;
  &lt;/xml&gt;
  </code></pre>
  
  <p>The result is nothing, no validation errors whatsoever. How do I fix it?</p>