Reputation: 19
How can i add a "xsi:Enumeration" XSD using C#
this is the base file 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>
and i wanna to get this result using 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>
Thanks :)
Upvotes: 1
Views: 1116
Reputation: 2771
You can edit an xsd file using System.xml.schema classes. Detailed example can be found on this support link.
http://support.microsoft.com/kb/318502/en-us
Here is modified code for adding two enumerations into the file and resaving the file.
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();
}
Upvotes: 1