1

如何使用 C# 添加“xsi:Enumeration”XSD

这是基本文件 XSD:

<xs:schema xmlns="urn:bookstore-schema"
     targetNamespace="urn:bookstore-schema"
     xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="TagType">
    <xs:restriction base="xs:string">
             <!--here to add new Enum elements -->
    </xs:restriction>
</xs:simpleType>

我想用 c# 得到这个结果:

<xs:schema xmlns="urn:bookstore-schema"
     targetNamespace="urn:bookstore-schema"
     xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="TagType">
    <xs:restriction base="xs:string">
        <xs:enumeration value="Actor" />
        <xs:enumeration value="Productor" />
        <xs:enumeration value="Director" />
        <xs:enumeration value="Category" />
    </xs:restriction>
</xs:simpleType>

谢谢 :)

4

1 回答 1

1

您可以使用 System.xml.schema 类编辑 xsd 文件。可以在此支持链接上找到详细示例。

http://support.microsoft.com/kb/318502/en-us

这是修改后的代码,用于将两个枚举添加到文件中并重新保存文件。

FileStream fs;
XmlSchema schema;
ValidationEventHandler eventHandler = 
    new ValidationEventHandler(Class1.ShowCompileErrors);

try
{
    fs = new FileStream("book.xsd", FileMode.Open);
    schema = XmlSchema.Read(fs, eventHandler);
    schema.Compile(eventHandler);

    XmlSchemaSet schemaSet = new XmlSchemaSet();
    schemaSet.Add(schema);
    schemaSet.Compile();
    schema = schemaSet.Schemas().Cast<XmlSchema>().First();

    var simpleTypes =
        schema.SchemaTypes.Values
            .OfType<XmlSchemaSimpleType>()
                .Where(t => t.Content is XmlSchemaSimpleTypeRestriction);

    foreach (var simpleType in simpleTypes)
    {
        XmlSchemaSimpleTypeRestriction restriction = 
        (XmlSchemaSimpleTypeRestriction)simpleType.Content;

        XmlSchemaEnumerationFacet actorEnum = 
            new XmlSchemaEnumerationFacet();

        actorEnum.Value= "Actor";
        restriction.Facets.Add(actorEnum);
        XmlSchemaEnumerationFacet producerEnum = 
            new XmlSchemaEnumerationFacet();

        producerEnum.Value = "Producer";
        restriction.Facets.Add(producerEnum);                       
    }

    fs.Close();
    fs = new FileStream("book.xsd", FileMode.Create);
    schema.Write(fs);
    fs.Flush();
    fs.Close();
}
catch (XmlSchemaException schemaEx)
{
    Console.WriteLine(schemaEx.Message);
}
catch (XmlException xmlEx)
{
    Console.WriteLine(xmlEx.Message);
}
    catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    Console.Read();
}
于 2013-03-26T09:38:09.187 回答