Validation

  • Thread starter Thread starter csharpula csharp
  • Start date Start date
C

csharpula csharp

Hello,
I would like to know if there is a way to validate xml file using xsd or
some other way for the following case:

Xml element represented by string value which need to be validated
against some strings domain . For example the element can be pnly one of
: "Applicatipn","User" or "None" any other value need to throw exception
in serialization stage. Is it possible?

Thank u!
 
Yes twice.
In C# use an enum (the nic easy option); in pure xsd, use xs:enumeration
elements (with value attributes) inside an xs:restriction with
base="xs:string".

Marc
 
I am trying to do this:

<xs:complexType name="ClassParent">
<xs:sequence>
<xs:element name="Name"><xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:sequence>

If in xml I am passing some other value in Name variable such as "ABC"
istead of Audi,Golf or BMW - I don't get any error while validating xml
with this scheme. why?

Thank u!
 
Well, for starters your xml is malformed (no </xs:element></xs:simpleType>)

This works (note the "" is just because of C# string-literal escaping) -
change the Name to something invalid and it tells you...

using System.IO;
using System.Xml;
using System.Xml.Schema;
static class Program
{
const string XSD = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema
xmlns=""""
xmlns:xs=""http://www.w3.org/2001/XMLSchema"">

<xs:element name=""foo"" type=""ClassParent""/>

<xs:complexType name=""ClassParent"">
<xs:sequence>
<xs:element name=""Name""><xs:simpleType>
<xs:restriction base=""xs:string"">
<xs:enumeration value=""Audi""/>
<xs:enumeration value=""Golf""/>
<xs:enumeration value=""BMW""/>
</xs:restriction>
</xs:simpleType></xs:element>
</xs:sequence>
</xs:complexType>

</xs:schema>";

const string XML = @"<foo><Name>Audi</Name></foo>";

static void Main()
{
XmlSchemaSet ss = new XmlSchemaSet();
ss.Add(null, XmlReader.Create(new StringReader(XSD)));

XmlReaderSettings rs = new XmlReaderSettings();
rs.Schemas = ss;
rs.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create(new StringReader(XML), rs);
while (reader.Read()) ;

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top