首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用C#添加"xs:Enumeration“XSD

使用C#添加"xs:Enumeration“XSD
EN

Stack Overflow用户
提问于 2013-03-26 17:33:52
回答 1查看 1K关注 0票数 1

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

这是基本文件XSD:

代码语言:javascript
复制
<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#得到这样的结果:

代码语言:javascript
复制
<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>

谢谢:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-26 17:38:09

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

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

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

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15633574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档