我正在编写一段代码,它试图读入一堆xsd文件,并在XmlSchemaSet中编译模式。
问题是这些xsd文件来自不同的来源,它们可能有多次声明的元素/类型,我应该删除这些元素/类型,否则XmlSchemaSet的compile方法将抛出错误。
有没有推荐的方法来做这类事情?
发布于 2011-10-25 13:10:23
我遵循了这篇MSDN帖子中的步骤,它对我很有效:
http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/7f1b7307-98c8-4457-b02b-1e6fa2c63719/
基本思想是遍历新模式中的类型,如果它们存在于现有模式中,则将它们从该模式中删除。
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;
}
}https://stackoverflow.com/questions/6312154
复制相似问题