views:

623

answers:

2

Howdy,

I need to validate a XML file against a schema. The XML file is being generated in code and before I save it I need to validate it to be correct.

I have stripped the problem down to its barest elements but am having an issue.

XML:

<?xml version="1.0" encoding="utf-16"?>
<MRIDSupportingData xmlns="urn:GenericLabData">
  <MRIDNumber>MRIDDemo</MRIDNumber>
  <CrewMemberIdentifier>1234</CrewMemberIdentifier>
  <PrescribedTestDate>1/1/2005</PrescribedTestDate>
</MRIDSupportingData>

Schema:

<?xml version="1.0" encoding="utf-16"?>
<xs:schema xmlns="urn:GenericLabData" targetNamespace="urn:GenericLabData" 
   xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;

   <xs:element name="MRIDSupportingData">
   <xs:complexType> 
      <xs:sequence>
        <xs:element name="MRIDNumber" type="xs:string" /> 
        <xs:element minOccurs="1" name="CrewMemberIdentifier" type="xs:string" />
      </xs:sequence>
   </xs:complexType>
  </xs:element>
</xs:schema>

ValidationCode: (This code is from a simple app I wrote to test the validation logic. The XML and XSD files are stored on disk and are being read from there. In the actual app, the XML file would be in memory already as an XmlDocument object and the XSD would be read from an internal webserver.)

private void Validate()
{
  XmlReaderSettings settings = new XmlReaderSettings();
  settings.ValidationType = ValidationType.Schema;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
  //settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
  settings.ValidationEventHandler += new ValidationEventHandler(OnValidate);

  XmlSchemaSet schemas = new XmlSchemaSet();
  settings.Schemas = schemas;
  try
  {
    schemas.Add(null, schemaPathTextBox.Text);
    using (XmlReader reader = XmlReader.Create(xmlDocumentPathTextBox.Text, settings))
    {
      validateText.AppendLine("Validating...");
      while (reader.Read()) ;
      validateText.AppendLine("Finished Validating");
      textBox1.Text = validateText.ToString();
    }
  }
  catch (Exception ex)
  {
    textBox1.Text = ex.ToString();
  }

}

StringBuilder validateText = new StringBuilder();
private void OnValidate(object sender, ValidationEventArgs e)
{
  switch (e.Severity)
  {
    case XmlSeverityType.Error:
      validateText.AppendLine(string.Format("Error: {0}", e.Message));
      break;
    case XmlSeverityType.Warning:
      validateText.AppendLine(string.Format("Warning {0}", e.Message));
      break;
  }
}

When running the above code with the XML and XSD files defined above I get this output:

Validating... Error: The element 'MRIDSupportingData' in namespace 'urn:GenericLabData' has invalid child element 'MRIDNumber' in namespace 'urn:GenericLabData'. List of possible elements expected: 'MRIDNumber'. Finished Validating

What am I missing? As far as I can tell, MRIDNumber is MRIDNumber so why the error?

The actual XML file is much larger as well as the XSD, but it fails at the very beginning, so I have reduced the problem to almost nothing.

Any assistance on this would be great.

Thank you,
Keith


BTW, These files do work:

XML:

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book genre="novel">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
</bookstore>

Schema:

  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">
  <xsd:element name="bookstore">
    <xsd:complexType>
      <xsd:sequence >
        <xsd:element name="book"  maxOccurs="unbounded">
          <xsd:complexType>
            <xsd:sequence >
              <xsd:element name="title" type="xsd:string"/>
              <xsd:element name="author">
                <xsd:complexType>
                  <xsd:sequence >
                    <xsd:element name="first-name"  type="xsd:string"/>
                    <xsd:element name="last-name" type="xsd:string"/>
                  </xsd:sequence> 
                </xsd:complexType>
              </xsd:element>
              <xsd:element name="price"  type="xsd:decimal"/>
            </xsd:sequence> 
            <xsd:attribute name="genre" type="xsd:string"/>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>    
    </xsd:complexType>   
  </xsd:element>
</xsd:schema>
+1  A: 

In the small excerpt of XML/XSD you are currently testing, did you include PrescribedTestDate in the XSD as well?

Tarnschaf
It doesn't matter if PrescribedTestDate is in the XML file or not. The error is the same, stopping at the MRIDNumber element.
Keith Sirmons
I'm not sure why you'd get an error referencing MRIDNumber if the issue is the PrescribedTestDate, but the difference I see in your generated XML and the working XML (as well as the XSD) is that neither the working XML nor the XSD contains PrescribedTestDate. I'd makd sure it's there and see if the error goes away.
AllenG
The issue wasn't the PrescribedTestDate.
Keith Sirmons
A: 

Try adding elementFormDefault="qualified" attribute in the xs:schema element of your XSD file.

I think the validator is saying that it wants a MRIDNumber element with no namespace, instead of your MRIDNumber element with namespace urn:GenericLabData.

streetpc
Tried it and it works.... So why does this fix the problem?
Keith Sirmons
Edited that in my answer: in the previous version of your XSD, the MRIDNumber element was not qualified (didn't belong to the target/default namespace). See this link: http://www.xfront.com/DefaultNamespace.html
streetpc
PS: if it works, please indicate this post as the answer to your question so that other users can find it when they have the same problem...
streetpc