473,809 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XML object serialization to MemoryStream and then XSD validation

Ok I have a class called Product
=============== =============== =============== =
Code: Product.vb
=============== =============== =============== =
Imports System.Xml.Seri alization
<XmlRootAttribu te(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:complexTyp e>
<xsd:sequence >
<xsd:element name="ProductNa me" type="xsd:strin g" />
</xsd:sequence>
</xsd:complexType >
</xsd:element>
</xsd:schema>
=============== =============== =============== ==

Heres my code thus far
=============== =============== =============== ==
myModule.vb
=============== =============== =============== ==
Imports System.Xml
Imports System.Xml.Sche ma
Imports System.Xml.Seri alization
Imports System.IO

Module myModule

Private isValid As Boolean = True
Sub Main()

Dim xs As XmlSerializer
xs = New XmlSerializer(G etType(product) )

Dim objProduct As New product
objProduct.Prod uctName = "QWERTY"

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

Dim xtr As XmlTextReader = _
New XmlTextReader(m s)

Dim xvr As New XmlValidatingRe ader(xtr)

xvr.ValidationT ype = ValidationType. Schema
xvr.Schemas.Add ("x", "Product.xs d")

AddHandler xvr.ValidationE ventHandler, _
AddressOf MyValidationEve ntHandler

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

xvr.Close()

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

'============== =============== =============== ===
' Sub: MyValidationEve ntHandler
'============== =============== =============== ===
Public Sub MyValidationEve ntHandler( _
ByVal sender As Object, _
ByVal args As ValidationEvent Args)
isValid = False
Console.WriteLi ne("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

Nov 12 '05 #1
5 3349


dickster wrote:

Dim xs As XmlSerializer
xs = New XmlSerializer(G etType(product) )

Dim objProduct As New product
objProduct.Prod uctName = "QWERTY"

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


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/
Nov 12 '05 #2
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 XmlValidatingRe ader(New XmlTextReader(m s))
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 ***
Nov 12 '05 #3
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)
=============== =============== =============== ==============

Nov 12 '05 #4


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


That could be a case issue, you have
<XmlRootAttribu te(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/
Nov 12 '05 #5
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.x sd" in the attributes of the product class

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

(setting a namespace attribute like xsi:noNamespace SchemaLocation=
"Products.x sd" 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.ValidationT ype = ValidationType. Schema
xvr.Schemas.Add ("x","products. xsd")
=============== =============== =============== ===============

Nov 12 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8093
by: Chrigel | last post by:
Hi all, We have problems deseralizing objects previously serialized as XML. This did work fine with .NET 1.1 but since we have installed SP1, deserializing fails (but serializing works). The error occurs within the following line "return formatter.Deserialize(xmlReader) as ParameterList;" and the "innerexception" sais "The root element is missing.". Thanks for any hints
5
7591
by: Mark Rae | last post by:
Hi, Can anyone please tell me how to convert an object say, a System.Web.Mail.MailMessage object, to a byte array and then convert the byte array to a Base64 string? Any assistance gratefully received. Best regards,
8
12668
by: rawCoder | last post by:
Hi All, I need some advanced samples or references for passing custom objects over the network using sockets. Without using Remoting what are other options in .NET Framework for this binary serialization. Thank You rawCoder
2
7996
by: ce | last post by:
Being a newbie regarding serialization and memorystreams, I was trying to see if i could improve page performance (avoiding going to the db on a postback) by saving my serialized business object in viewstate and getting it back from the client on a postback. But the last line of the sample code below throws a "Stream was not readable" error when i'm trying to get the serialized object back out of the viewstate and memorystream. Any...
5
4043
by: Daniel Walzenbach | last post by:
Hi, I need to track all changes made to an object. Consider the following class: Public Class Dog
4
1415
by: DazedAndConfused | last post by:
I encryted a serialized binary formatted object. Now I can't figure out how to deserialize it so that I can decrypt it. I used this code encrypt and write it out: Dim fe As New MortgageFileWriter.FileEncrypt Dim myBuffer As New IO.MemoryStream Dim OutBuffer As New IO.MemoryStream
1
5555
by: J. Askey | last post by:
I am implementing a web service and thought it may be a good idea to return a more complex class (which I have called 'ServiceResponse') in order to wrap the original return value along with two other properties... bool error; string lastError; My whole class looks like this... using System;
6
45726
by: Val | last post by:
How can I serialize/deserialize an object into a string. Existing examples seem to be showing this operation for files only. Thansk
2
11541
by: Thomas S | last post by:
Any suggestions on how to deserialize an object from one line of XML? I'm trying to deserialize multiple objects from one XML document, each object on one line of the file. The serialization is working, but when I try to read the line back into a MemoryStream, and then to deserialize from that, I get an error that the root node doesn't exist. Example XML lines: <?xml version="1.0"?><LogItem
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10639
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10383
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7661
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.