Connecting Tech Pros Worldwide Help | Site Map
 
 
LinkBack Thread Tools Search this Thread
  #1  
Old November 12th, 2005, 04:39 AM
dickster
Guest
 
Posts: n/a
Default XML object serialization to MemoryStream and then XSD validation

Ok I have a class called Product
==============================================
Code: Product.vb
==============================================
Imports System.Xml.Serialization
<XmlRootAttribute(ElementName:="product", [Namespace]:="x")> _
Public Class product
Public _product_name As String
End Class
==============================================



I want to serialize an instance of this class to XML
and validate it against the following product.xsd
saved in the \bin folder
===============================================
Product.xsd
===============================================
<?xml version="1.0"?>
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="x">
<xsd:element name="Product">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ProductName" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
===============================================



Heres my code thus far
===============================================
myModule.vb
===============================================
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.Serialization
Imports System.IO

Module myModule

Private isValid As Boolean = True
Sub Main()

Dim xs As XmlSerializer
xs = New XmlSerializer(GetType(product))

Dim objProduct As New product
objProduct.ProductName = "QWERTY"

Dim ms As New MemoryStream
xs.Serialize(ms, objProduct)

Dim xtr As XmlTextReader = _
New XmlTextReader(ms)

Dim xvr As New XmlValidatingReader(xtr)

xvr.ValidationType = ValidationType.Schema
xvr.Schemas.Add("x", "Product.xsd")

AddHandler xvr.ValidationEventHandler, _
AddressOf MyValidationEventHandler

Try
While xvr.Read()
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try

xvr.Close()

' Check whether the document is valid or invalid.
If (isValid) Then
Console.WriteLine("Document is valid")
Else
Console.WriteLine("Document is invalid")
End If
End Sub

'===============================================
' Sub: MyValidationEventHandler
'===============================================
Public Sub MyValidationEventHandler( _
ByVal sender As Object, _
ByVal args As ValidationEventArgs)
isValid = False
Console.WriteLine("Validation event\n" + args.Message)
End Sub

End Module
===============================================



Q1. Am I using the namespaces properly?
Q2. The serialisation to MemoryStream is binary perhaps this is my
problem

Much appreciated if someone could correct this code - or point me in
the direction of a solution

  #2  
Old November 12th, 2005, 04:39 AM
Martin Honnen
Guest
 
Posts: n/a
Default Re: XML object serialization to MemoryStream and then XSD validation



dickster wrote:

[color=blue]
> Dim xs As XmlSerializer
> xs = New XmlSerializer(GetType(product))
>
> Dim objProduct As New product
> objProduct.ProductName = "QWERTY"
>
> Dim ms As New MemoryStream
> xs.Serialize(ms, objProduct)[/color]

You have not told us what goes wrong but I think you need to reposition
the memory stream to the start with e.g.
ms.Position = 0
here before you try to read in the stream for validation.



--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
  #3  
Old November 12th, 2005, 04:39 AM
student
Guest
 
Posts: n/a
Default Re: XML object serialization to MemoryStream and then XSD validation

Many thanks for your reply Martin

The Error I originally got was as follows
When we hit:

While v.Read()
' running through the XML document to ensure validity
End While

An exception is thrown and details as follows
ex.Message = "The root element is missing"


Thanks to your reply by setting the memory stream position to the
beginning

i.e ms.positon=0

My code now seems to pick up the root element

However I now get the two following error messages in the console window
================================================== =========
Validation event\n The 'message' element is not declared an error
occurred at (2,2)
Validation event\n The 'ProductName' element is not declared an error
occurred at (4,3)
================================================== =========

Is this do do with the fact that memoryStream is a binary representation
of the serialised XML? Is this why it does not validate against the
product.xsd

To be honest I havent fully grasped "streams" and the Sytem.IO stuff

Perhaps "ms" should be converted from binary to UTF-8 before being
passed to the
declaration of XmlValidatingReader(New XmlTextReader(ms))


As an aside:
To demonstrate that the MemortStream is binary but does indeeed contain
my serialised object as XML,I have been able to convert the memorystream
(ms) to a byte array using ms.toArray() and then convert that Byte Array
to a String and show the XML i expect out in the console






*** Sent via Developersdex http://www.developersdex.com ***
  #4  
Old November 12th, 2005, 04:39 AM
dickster
Guest
 
Posts: n/a
Default Re: XML object serialization to MemoryStream and then XSD validation

Correction: the error messages read as follows:
================================================== =========
Validation event\n The 'product' element is not declared an error
occurred at (2,2)
Validation event\n The 'ProductName' element is not declared an error
occurred at (4,3)
================================================== =========

  #5  
Old November 12th, 2005, 04:39 AM
Martin Honnen
Guest
 
Posts: n/a
Default Re: XML object serialization to MemoryStream and then XSD validation



dickster wrote:
[color=blue]
> Correction: the error messages read as follows:
> ================================================== =========
> Validation event\n The 'product' element is not declared an error
> occurred at (2,2)[/color]

That could be a case issue, you have
<XmlRootAttribute(ElementName:="product"
but the schema declares
<xsd:element name="Product">
so you have to change the case of the 'p', use 'Product' in both
locations or 'product' in both locations.


--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
  #6  
Old November 12th, 2005, 04:39 AM
dickster
Guest
 
Posts: n/a
Default Re: XML object serialization to MemoryStream and then XSD validation

Thats it working now :-)

- many thanks for your solutions, time and effort

It is indeed Case Sensitive and functions as expected when the
correction is made.

The MemoryStream did indeed also need to be set to the start i.e.
..position=0 as shown in previous post

Thanks again!!

************************************************** ****************************
Another thing I've learnt along the way (which appears so obvious when
I think about it now) is that there is no need to worry about setting
the
SchemaLocation= "Products.xsd" in the attributes of the product class

i.e. <XmlRootAttribute(ElementName:="product", [Namespace]:="x"
<<????>> )> _

(setting a namespace attribute like xsi:noNamespace SchemaLocation=
"Products.xsd" is not supported by .NET serialisation - or thats how I
read it from MSDN)

but the .xsd is associated with the .xml here and here alone
================================================== ==========
xvr.ValidationType = ValidationType.Schema
xvr.Schemas.Add("x","products.xsd")
================================================== ==========

 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

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

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 205,248 network members.