You may have noticed me blogging about circular imports when trying to validate an Open XML document against the supplied XSD's. At the moment I am using the XSD's to determine the correct insert positions of new nodes when building documents dynamically, and I still come across the circular import problem.
I did have one instance in which the circular problem didn't exist, but I believe I had the imported schemas in the wrong directory so they were not imported at all. Let me blog about this later, I believe it is a bug in the XmlSchemaSet.
So still the circularity problem, kinda anoying. But I believe to have a working solution. Now this solution might not be iron-clad though, but it does work perfectly for me in my current situation (resolving circular imports).
My solution? The XmlResolver class! When you add a schema to an XmlSchemaSet, the XmlSchemaSet will need to resolve the correct Uri for the imported XmlSchema. For this it uses an instance of the XmlResolver class. If you implement your own XmlResolver you can determine where the schemas should be loaded from. Now the nice thing about this Uri resolution is that if you return null from the method which performs the resolution, the schema will be skipped by the XmlSchemaSet. This enables us to monitor which schemas have been resolved, and when one schema is being resolved for the second time, just return null to skip it.
Now in code this looks like the following:
class MyXmlResolver : XmlResolver
{
List<Uri> _resolvedUris = null;
public override System.Net.ICredentials Credentials
{
set { throw new Exception("The method or operation is not implemented."); }
}
public override Uri ResolveUri(Uri baseUri, string relativeUri)
{
Uri resolvedUri = MyMethodToResolveUri(baseUri, relativeUri)
if(_resolvedUris.Find(
delegate(Uri i)
{
return String.Equals(
resolvedUri.ToString(), i.ToString(), StringComparison.InvariantCultureIgnoreCase);
}) != null)
{
return null;
}
return resolvedUri;
}
public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
{
_resolvedUris.Add(absoluteUri);
// code to get xmlschema
}
}
Hope this helps!
Posted
08-10-2006 11:22
by
Anonymous