Hi,
I am finding diffcult to validate a xml fragment to validate against a schema.
The situation is as follows:
I am making an xml string on the fly, but before submitting it to another server, I need to validate that it is a valid xml against schema. I have the schema saved locally on the server. Here is the xml:
Code:
<?xml version='1.0' encoding='UTF-8'?>
<portalReq xmlns='http://www.e-paycapita.com/portal'>
<requestID>1234</requestID>
<language>en</language>
<source>l</source>
<returnURL>http://www.portsmouth.gov.uk</returnURL>
<backURL>http://bbc.co.uk</backURL>
<cart>
<items><item itemNumber='1'>
<reference>CTax123</reference>
<fundCode>05</fundCode>
<accountName>Mr. A J Kaul</accountName>
<amount>112.56</amount>
</item>
</items>
</cart>
</portalReq>
I have attached the schema file as .txt with this post.
I have come across XmlValidatingReader class and tried to use it, but even if I take out one required element from xml, it does not produce error: Following is the code:
Code:
Private Function ValidateXML(ByVal objStr As StringReader)
Dim reader As XmlValidatingReader = Nothing
Dim myschema As New XmlSchemaCollection
Try
'Create the XML fragment to be parsed.
Dim xmlFrag As String = objStr.ReadToEnd
'Create the XmlParserContext.
Dim context As New XmlParserContext(Nothing, Nothing, "", XmlSpace.None)
'Implement the reader.
reader = New XmlValidatingReader(xmlFrag, XmlNodeType.Element, context)
'Add the schema.
Dim strXSD As String = Server.MapPath("abc.xsd")
myschema.Add("http://www.abc.com/abc", strXSD)
'Set the schema type and add the schema to the reader.
reader.ValidationType = ValidationType.Schema
reader.Schemas.Add(myschema)
'Add the handler to raise the validation event.
AddHandler reader.ValidationEventHandler, AddressOf Me.ValidationEventHandle
While reader.Read
End While
Label1.Text = Label1.Text + "Completed validating xmlfragment"
Catch XmlExp As XmlException
Label1.Text = Label1.Text + XmlExp.Message
Catch XmlSchExp As XmlSchemaException
Label1.Text = Label1.Text + XmlSchExp.Message
Catch GenExp As Exception
Label1.Text = Label1.Text + GenExp.Message
End Try
End Function
Public Sub ValidationEventHandle(ByVal sender As Object, ByVal args As ValidationEventArgs)
m_success = False
Console.WriteLine((ControlChars.CrLf & ControlChars.Tab & "Validation error: " & args.Message))
End Sub 'ValidationEventHandle
Private Function validateXML(ByVal xml As String)
Try
'Is the xml string valid?
If (xml Is Nothing Or xml.Length < 1) Then
Return False
End If
Dim srXml As StringReader = New StringReader(xml)
Return validateXML(srXml)
Catch ex As Exception
ValidationError = ex.Message
Return False
End Try
End Function
Public Property ValidationError()
Get
Return "<ValidationError>" + ValidationError + "</VALIDATIONERROR>"
End Get
Set(ByVal Value)
ValidationError = Value
End Set
End Property
Public Sub validationCallBack(ByVal sender As Object, ByVal args As ValidationEventArgs)
Label1.Text = "Error:" + args.Message
End Sub
Please help!!