3

When I load a XMLSchema through the following code:

_XmlDocument = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

XmlReader reader = XmlReader.Create(documentPath, settings);

_XmlDocument.Load(reader);
reader.Close();
XmlSchema schema = _XMLDocument.Schemas.Schemas().OfType<XmlSchema>().FirstOrDefault();

and do the following unit test code:

Assert.IsNotNull(schema);
Assert.AreEqual(this.schemaSourceURI, schema.SourceUri);

XmlSchemaElement queryElement = schema.Elements.Values.OfType<XmlSchemaElement>().Where(e => e.Name.Equals("QUERY")).FirstOrDefault();
Assert.IsNotNull(queryElement);
Assert.IsTrue(queryElement.Constraints.OfType<XmlSchemaKey>().Count() > 0);
Assert.IsTrue(queryElement.Constraints.OfType<XmlSchemaKeyref>().Count() > 0);

everything works fine.

When I load the xsd schema by

XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add("http://www.w3.org/2001/XMLSchema", file);
schemaSet.Compile();

return schemaSet.Schemas().OfType<XmlSchema>().FirstOrDefault();

XmlSchema schema = schemaSet.Schemas().OfType<XmlSchema>().FirstOrDefault();

then both Assert.IsTrue from the unit test code(above) fail. I load the same file both times.

How do I get XmlSchemaSet to load key constraints? Both schemas are from the same file(.SourceUri are both this.schemaSourceURI).

simsi
  • 533
  • 3
  • 16
  • Make sure you receive the entire schema before processing the schema. You have an asynchronous event and you must block waiting for the entire file before processing. – jdweng Dec 23 '16 at 12:10
  • Thank you for your answer! Which method is asynchronus? The documentation has nothing about it. Also not how i can wait for it. – simsi Dec 24 '16 at 11:03
  • I think you simply have to reverse the 2nd and 3rd line so you add the schema, add the event handler, and then compile. Adding the event handler before reading the schema is probably giving a validation call back error. – jdweng Dec 24 '16 at 11:12
  • Thanks, but there is no validation error. MS does it in their examples in the same way I do: https://msdn.microsoft.com/de-de/library/ms255932(v=vs.110).aspx. – simsi Dec 29 '16 at 08:58
  • If you load the same file both times do you close it in-between? The error may be caused by opening the same file twice. – jdweng Dec 29 '16 at 10:44
  • I have already found the answer(see below), thank you for your help! – simsi Dec 29 '16 at 10:52

1 Answers1

2

I don't know why but schemaSet.Add(null, file) with null instead of "http://www.w3.org/2001/XMLSchema" fixed it for me.

simsi
  • 533
  • 3
  • 16