Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSchema removing duplicate types

Tags:

c#

xsd

I am working on a code that is trying to read in a bunch of xsd files and compiling schemas in a XmlSchemaSet.

Problem is that these xsd files come from various sources, and they might have elements/types declared multiple times, which i should remove or else i the compile method of XmlSchemaSet would throw an error.

Is there a recommended way of doing this type of thing ?

like image 892
np-hard Avatar asked May 24 '26 04:05

np-hard


1 Answers

I followed steps from this MSDN post and it worked for me:

http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/7f1b7307-98c8-4457-b02b-1e6fa2c63719/

The basic idea is to go through the types from the new schema and remove them from that schema if they exist in the existing schema.

 class Program
  {
    static void Main(string[] args)
    {
      XmlSchemaSet schemaSet = MergeSchemas(@"..\..\XMLSchema1.xsd", @"..\..\XMLSchema2.xsd");
      foreach (XmlSchema schema in schemaSet.Schemas())
      {
        schema.Write(Console.Out);
        Console.WriteLine();
      }
    }

    public static XmlSchemaSet MergeSchemas(string schema1, string schema2)
    {
      XmlSchemaSet schemaSet1 = new XmlSchemaSet();
      schemaSet1.Add(null, schema1);
      schemaSet1.Compile();

      XmlSchemaSet schemaSet2 = new XmlSchemaSet();
      schemaSet2.Add(null, schema2);
      schemaSet2.Compile();

      foreach (XmlSchemaElement el1 in schemaSet1.GlobalElements.Values)
      {
        foreach (XmlSchemaElement el2 in schemaSet2.GlobalElements.Values)
        {
          if (el2.QualifiedName.Equals(el1.QualifiedName))
          {
            ((XmlSchema)el2.Parent).Items.Remove(el2);
            break;
          }
        }
      }
      foreach (XmlSchema schema in schemaSet2.Schemas())
      {
        schemaSet2.Reprocess(schema);
      }
      schemaSet2.Compile();
      schemaSet1.Add(schemaSet2);

      return schemaSet1;
    }
  }
like image 143
Igor Zevaka Avatar answered May 26 '26 18:05

Igor Zevaka