Groups | Blog | Home
all groups > dotnet xml > august 2004 >

dotnet xml : serialisation of classes to generate XMLDocument


Stephen
8/24/2004 2:43:03 AM
I need to generate input XML for another application by serialising classes
defined in an XSD document. The code below will generate the XML I require
but I need to generate this in memory rather than creating a file. I assume
I should be using System.IO.MemoryStream but can't get this to work.

' XML will be serialized to file.xml, in UTF-8, with BOM.
Dim tw As New System.Xml.XmlTextWriter( _
New System.IO.FileStream("file.xml",
System.IO.FileMode.Create), _
New System.Text.UTF8Encoding(True))
ser.Serialize(tw, domainObj.getGMPApp)
' Finish writing the file and close it.
tw.Flush()
tw.Close()
xmlDoc.Load("file.xml")

Dino Chiesa [Microsoft]
8/24/2004 6:25:40 PM
how about serializing to a string?

<!--StartFragment-->
XmlSerializer s1 = new XmlSerializer(typeof(MyType));
System.IO.StringWriter sw = new System.IO.StringWriter();
s1.Serialize(sw, instance);
// sw.ToString() now holds the XML ...


[quoted text, click to view]

Stephen
8/25/2004 1:27:02 AM
dino
this generates XML with encoding iof UTF-16 whch I can't load into the XML
documentthat I want to. The code that generates the file will generate the
XML with the correct encoding but what I want too be able to do is generate
this in code.


[quoted text, click to view]
Dino Chiesa [Microsoft]
8/25/2004 8:06:24 AM
my bad...

Dim ms As New System.IO.MemoryStream()
Dim tw2 As New System.Xml.XmlTextWriter( ms, utf8 )
Try
ser.Serialize(tw2, dto1)
tw2.Flush()
ms.Seek(0, System.IO.SeekOrigin.Begin)

Dim byteArray as Byte()
byteArray= New Byte(CType(ms.Length, Integer)){}
Dim count As Integer
count = 0

' Read the Bytes, Byte by Byte.
While(count < ms.Length)
byteArray(count) = _
System.Convert.ToByte(ms.ReadByte())
count += 1
End While

' Decode the Byte array into a Char array
' and write it to the console.
Dim charArray as Char()
charArray = _
New Char(utf8.GetCharCount(byteArray, 0, count)){}
utf8.GetDecoder().GetChars( byteArray, 0, count, charArray, 0)
System.Console.WriteLine(charArray)

Finally
ms.Close()
tw2.Close()
End Try




[quoted text, click to view]

Stephen
8/26/2004 3:39:05 AM
Dino
thank U for the code below, which when I run it generates the required XML
in the charArray. However I am still having problems using this XML. What I
want to do is take this XML and use it in an XSL transformation to generate
the input XML for another application. Do you know what I need to do to load
the serialised XML into something that the transform can use?
..
..
Dim xslt As New Xml.Xsl.XslTransform
Dim xr As Xml.XmlResolver
Dim transformXSL As [String] = "transform.xsl"
xslt.Load(transformXSL)
writer.Formatting = Xml.Formatting.Indented
xslt.Transform(---- XML ----, Nothing, ---Output XM L---, Nothing)



[quoted text, click to view]
AddThis Social Bookmark Button