Current location: Hot Scripts Forums » Programming Languages » Windows .NET Programming » RegEx, XSD and DataSet


RegEx, XSD and DataSet

Reply
  #1 (permalink)  
Old 08-11-10, 09:54 AM
MikeTims MikeTims is offline
New Member
 
Join Date: Aug 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
RegEx, XSD and DataSet

i have a XSD file that includes the simple types

Code:
    <xs:simpleType name="PhoneNo">
        <xs:restriction base="xs:string">
            <xs:pattern value="0(1|2|3|7)\d+" />
            <xs:maxLength value="11" />
            <xs:minLength value="10" />
        </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="Email">
        <xs:restriction base="xs:string">
            <xs:pattern value=".+@.+\.\w+" />
        </xs:restriction>
    </xs:simpleType>
and the element

Code:
   <xs:element name="Input" msdata:IsDataSet="true" msdata:Locale="en-GB">
        <xs:complexType>
            <xs:choice minOccurs="1" maxOccurs="unbounded">
                <xs:element name="LeadDetails">
                    <xs:complexType>
                        <xs:attribute name="Title" type="xs:string" />
                        <xs:attribute name="FirstName" type="xs:string" />
                        <xs:attribute name="Surname" type="xs:string" use="required" />
                        <xs:attribute name="Phone1" type="PhoneNo" use="required" />
                        <xs:attribute name="Phone2" type="PhoneNo" />
                        <xs:attribute name="Phone3" type="PhoneNo" />
                        <xs:attribute name="EMail" type="Email" />
                    </xs:complexType>
                </xs:element>
            </xs:choice>
        </xs:complexType>
    </xs:element>
however when i load the xsd into a dataset using


Code:
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ds = New DataSet()
            Dim fi As New FileInfo(OpenFileDialog1.FileName)
            ds.ReadXmlSchema(fi.OpenRead())
        End If
and then feed in the xml

Code:
		dim xml as string = "<XMLData> <Input FirstName="someone" Surname="somewhere"  Phone1="01234567890" Phone3="09123456789" Email="someoneAtsomewhere.co.uk" /> </XMLData>"
		ds.ReadXml(New StringReader(xml))
		DataGridView1.DataSource = ds.Tables(0)
		DataGridView1.Refresh()
it lets both the 09 telephone number and the bad email through

what am i missing?
Reply With Quote
  #2 (permalink)  
Old 08-12-10, 04:07 AM
Yeroon's Avatar
Yeroon Yeroon is offline
Code Master
 
Join Date: Aug 2007
Location: Netherlands, Nijmegen
Posts: 850
Thanks: 2
Thanked 20 Times in 20 Posts
Hi there,

Try this code. I use it in my Apps and Websites and it never really fails. Note that I translated it from C# to VB.Net, but tested it in a Web Application in VB.Net and it was working. The Server.Mappath you can replace with an equivalent or just put full file path in the string part.

Code:
Private _validationErrors As New List(Of String)()

    ''' <summary> 
    ''' Get any error messages that were found validating the XML document against 
    ''' an XSD schema document. 
    ''' </summary> 
    Public ReadOnly Property ValidationErrors() As List(Of String)
        Get
            Return _validationErrors
        End Get
    End Property



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ValidateXmlAgainstSchema(Server.MapPath("~/XMLFile.xml"), Server.MapPath("~/XMLSchema.xsd"))

        If ValidationErrors().Count > 0 Then
            'something was wrong. Handle it
            Dim i As Integer = 0
        End If
    End Sub

    Public Sub ValidateXmlAgainstSchema(ByVal xmlFileName As String, ByVal xsdFileName As String)
        Using xsdReader As XmlReader = XmlReader.Create(xsdFileName)
            ' Read the schema from a file. 
            Dim schema As XmlSchema = XmlSchema.Read(xsdReader, AddressOf OnValidationEvent)

            ' Setup the XmlReader for schema validation. 
            Dim settings As New XmlReaderSettings()
            settings.ValidationType = ValidationType.Schema
            settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings

            AddHandler settings.ValidationEventHandler, AddressOf OnValidationEvent

            ' Add the schema document. 
            settings.Schemas.Add(schema)

            ' Read each element of the document. Any errors will raise a ValidationEvent. 
            Using reader As XmlReader = XmlReader.Create(xmlFileName, settings)
                While reader.Read()
                End While
            End Using
        End Using



    End Sub

    Private Sub OnValidationEvent(ByVal sender As Object, ByVal e As ValidationEventArgs)
        _validationErrors.Add(e.Message)
    End Sub
__________________
Feel free to thank people if they help you by clicking thanks at a post.
=================================
Make it idiot proof and someone will make a better idiot.
=================================
Realise the impotence of proof reading everything you publish
Reply With Quote
The Following User Says Thank You to Yeroon For This Useful Post:
m.timoney (08-12-10)
  #3 (permalink)  
Old 08-12-10, 04:13 AM
m.timoney's Avatar
m.timoney m.timoney is offline
Newbie Coder
 
Join Date: Jan 2007
Location: Leicester - UK
Posts: 76
Thanks: 1
Thanked 0 Times in 0 Posts
Question

thanks personally i perfer C# but people i work for are still using VB6 so not a chance of getting them onto a C based syntax. shifting to .net was a breakthrough

thats validating using a XML schema object so i take it that the part i'm missing is that the DataSet's XML schema implementation doesn't support the more advanced validation aspects that can be used in an xsd?
__________________
Definition of a Beginner, Someone who doesn't know the rules.

Definition of an Expert, Someone who knows when to ignore the rules.
Reply With Quote
  #4 (permalink)  
Old 08-12-10, 05:01 AM
Yeroon's Avatar
Yeroon Yeroon is offline
Code Master
 
Join Date: Aug 2007
Location: Netherlands, Nijmegen
Posts: 850
Thanks: 2
Thanked 20 Times in 20 Posts
Hi,

Yea you need to load the XSD as an XmlSchema. The validation mechanics in .Net require the XmlDocument to be validated versus that XmlSchema. If you want to use datasets, you will have to iterate through the rows and validate yourself.

Your ds.ReadXmlSchema(fi.OpenRead()) only reads it into a dataset, thus it contains data. No longer a schema to validate against.

You could use the Merge method of DataSet. If in the code below the dataset Result is not Nothing (null), then there were differences. Basically your create a DataSet from the XSD and your XML. Then try to merge both into a new DataSet (ds3). After you load the XSD, you accept changes, so the structure gets set. Then you merge the XML dataset. If it can't merge it, the GetChanges will put a dataset in Result.

Code:
Dim ds1 As New DataSet
        Dim ds2 As New DataSet
        Dim ds3 As New DataSet
        Dim fi As New FileInfo(Server.MapPath("~/XMLSchema.xsd"))
        Dim xml As String = "<XMLData> <Input FirstName=""someone""  Surname=""somewhere""  Phone1=""01234567890"" Phone3=""09123456789"" Email=""someoneAtsomewhere.co.uk"" /> </XMLData>"
        Dim result As DataSet
        

        ds1.ReadXmlSchema(fi.OpenRead())
        ds2.ReadXml(New StringReader(xml))

        ds3.Merge(ds1)
        ds3.AcceptChanges()
        ds3.Merge(ds2)
        result = ds3.GetChanges()
        Dim d As New DataTable


        For Each dr As DataRow In result.Tables(1).Rows
            Dim s As String
            s = dr(0)
        Next
__________________
Feel free to thank people if they help you by clicking thanks at a post.
=================================
Make it idiot proof and someone will make a better idiot.
=================================
Realise the impotence of proof reading everything you publish

Last edited by Yeroon; 08-12-10 at 05:05 AM.
Reply With Quote
  #5 (permalink)  
Old 08-12-10, 05:04 AM
m.timoney's Avatar
m.timoney m.timoney is offline
Newbie Coder
 
Join Date: Jan 2007
Location: Leicester - UK
Posts: 76
Thanks: 1
Thanked 0 Times in 0 Posts
thanks for confirming that
__________________
Definition of a Beginner, Someone who doesn't know the rules.

Definition of an Expert, Someone who knows when to ignore the rules.
Reply With Quote
  #6 (permalink)  
Old 08-12-10, 05:07 AM
Yeroon's Avatar
Yeroon Yeroon is offline
Code Master
 
Join Date: Aug 2007
Location: Netherlands, Nijmegen
Posts: 850
Thanks: 2
Thanked 20 Times in 20 Posts
Hi,

Was just thinking the dataset merge method will only show you structural errors. It will not validate content if the structure is correct.

So my first answer is the way to go I think.

/Yeroon
__________________
Feel free to thank people if they help you by clicking thanks at a post.
=================================
Make it idiot proof and someone will make a better idiot.
=================================
Realise the impotence of proof reading everything you publish
Reply With Quote
  #7 (permalink)  
Old 08-12-10, 05:22 AM
m.timoney's Avatar
m.timoney m.timoney is offline
Newbie Coder
 
Join Date: Jan 2007
Location: Leicester - UK
Posts: 76
Thanks: 1
Thanked 0 Times in 0 Posts
i'll have to rebuild one of their existing systems to do that with the schema object and if i do i'd probably leave the dataset where it is (if it ain't broke don't fix it) but validate the XML prior to the code feeding into it
__________________
Definition of a Beginner, Someone who doesn't know the rules.

Definition of an Expert, Someone who knows when to ignore the rules.
Reply With Quote
  #8 (permalink)  
Old 08-12-10, 05:55 AM
m.timoney's Avatar
m.timoney m.timoney is offline
Newbie Coder
 
Join Date: Jan 2007
Location: Leicester - UK
Posts: 76
Thanks: 1
Thanked 0 Times in 0 Posts
just to give you the back ground, people i work for have a webservice where data is fed into it and it then parses it through a dataset and dumps it into a database. the interesting thing is that the dump depends is dependent on which schema.is used, so the validation can't be hard coded. currently the data is validated in the DB but because of server load they want to do this before it hits the database and but with out changing the web service. hence why i was looking into if they schema could validate it
__________________
Definition of a Beginner, Someone who doesn't know the rules.

Definition of an Expert, Someone who knows when to ignore the rules.
Reply With Quote
  #9 (permalink)  
Old 08-12-10, 06:52 AM
Yeroon's Avatar
Yeroon Yeroon is offline
Code Master
 
Join Date: Aug 2007
Location: Netherlands, Nijmegen
Posts: 850
Thanks: 2
Thanked 20 Times in 20 Posts
Well the call to the webservice is a XML call. So you could validate it before trnasforming it to a dataset. I am looking through one of my projects now where i basically did the same thing. Will get back to you.
__________________
Feel free to thank people if they help you by clicking thanks at a post.
=================================
Make it idiot proof and someone will make a better idiot.
=================================
Realise the impotence of proof reading everything you publish
Reply With Quote
  #10 (permalink)  
Old 08-12-10, 07:10 AM
Yeroon's Avatar
Yeroon Yeroon is offline
Code Master
 
Join Date: Aug 2007
Location: Netherlands, Nijmegen
Posts: 850
Thanks: 2
Thanked 20 Times in 20 Posts
I was just thinking. You probably have a collection of XSD's for the datasets. Can't you put the incoming XML through all these schema's to see if one matches. If none match obviously they have a problem with the input, but when you do manage to validate one, you know what dataset is to be used.
__________________
Feel free to thank people if they help you by clicking thanks at a post.
=================================
Make it idiot proof and someone will make a better idiot.
=================================
Realise the impotence of proof reading everything you publish
Reply With Quote
Reply

Bookmarks

Tags
regex, xml, xsd


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump


All times are GMT -5. The time now is 02:19 PM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.