title: XML validation and namespaces in .NET
body: <p>What I'm trying to do is to validate XML against an XSD. This is all pretty straightforward, but I'm having a problem with XML's without a namespace.
  C# only validates the xml if the namespace matches the targetnamespace of the XSD. This seems right, but an XML with no namespace or a different one then the SchemaSet should give an exception. Is there a property or a setting to achieve this? Or do I have to get the namespace manually by reading the xmlns attribute of the xml?</p>
  
  <p>An example to clearify:</p>
  
  <p>Code:</p>
  
  <pre><code>XmlReaderSettings settings = new XmlReaderSettings();
  settings.Schemas.Add("http://example.com", @"test.xsd");
  settings.Schemas.Add("http://example.com/v2", @"test2.xsd");
  settings.ValidationType = ValidationType.Schema;
  
  XmlReader r = XmlReader.Create(@"test.xml", settings);
  
  XmlReader r = XmlReader.Create(new StringReader(xml), settings);
  XmlDocument doc = new XmlDocument();
  try
  {
      doc.Load(r);
  }
  catch (XmlSchemaValidationException ex)
  {
  
      Console.WriteLine(ex.Message);
  }
  </code></pre>
  
  <p>XSD:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com" targetNamespace="http://example.com" elementFormDefault="qualified" attributeFormDefault="unqualified"&gt;
      &lt;xs:element name="test"&gt;
          &lt;xs:annotation&gt;
              &lt;xs:documentation&gt;Comment describing your root element&lt;/xs:documentation&gt;
          &lt;/xs:annotation&gt;
          &lt;xs:simpleType&gt;
              &lt;xs:restriction base="xs:string"&gt;
                  &lt;xs:pattern value="[0-9]+\.+[0-9]+" /&gt;
              &lt;/xs:restriction&gt;
          &lt;/xs:simpleType&gt;
      &lt;/xs:element&gt;
  &lt;/xs:schema&gt;
  </code></pre>
  
  <p>Valid XML:</p>
  
  <pre><code>&lt;test xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;112.1&lt;/test&gt;
  </code></pre>
  
  <p>Invalid XML, this will not validate:</p>
  
  <pre><code>&lt;hello xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;112.1&lt;/hello&gt;
  </code></pre>
  
  <p>Error: <code>The 'http://example.com:hello' element is not declared</code>.</p>
  
  <p>Invalid XML, but will validate, because namespace is not present:</p>
  
  <pre><code>&lt;hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;112.1&lt;/hello&gt;
  </code></pre>
  
  <p>How can I fix this?</p>
  
  <p>Any help much appreciated.</p>