Removing XML Namespaces from XML Serialized Output - vb.net

I am generating this XML using the serializer in VB.net as shown below
Dim string_writer As New StringWriter()
Dim serializer As New XmlSerializer(GetType(MyClass))
serializer.Serialize(string_writer, addr)
txttest.Text = string_writer.ToString()
though it is returning XML, I see xmlns="http://tempuri.org/ in all the elements, is there anyway I hide this one.

Sure - just pass the default namespace you want to use to the constructor of your XmlSerializer:
Dim string_writer As New StringWriter()
Dim serializer As New XmlSerializer(GetType(MyClass), "")
serializer.Serialize(string_writer, addr)
txttest.Text = string_writer.ToString()
That should do the trick.

Related

{"Unexpected JSON token when reading DataTable. Expected StartArray, got Integer. Path 'id', line 1, position 9."}

Receiving below error on deserializing json to dataset.
Unexpected JSON token when reading DataTable. Expected StartArray, got Integer. Path 'id', line 1, position 9
Json Retrieved : {"id":130,"type":"general","setup":"test?","punchline":"test."}
My Code
Dim wc As New WebClient
Try
Dim res As String
For i = 0 To 5
res = wc.DownloadString("https://official-joke-api.appspot.com/random_joke")
Dim jObject = JsonConvert.DeserializeObject(res)
Dim ds As New DataSet
ds = JsonConvert.DeserializeObject(Of DataSet)(res)
MsgBox(ds.Tables.Count)
Next
Catch ex As Exception
MsgBox(ex)
End Try
As user Akshay Gaonkar commented, you can give Newtonsoft.Json a class, named, say, Joke, to deserialise with. You can get around the mismatch of uppercase/lowercase initial letter naming conventions by decorating the properties with <JsonProperty("nameInTheJson")>.
Instead of deserializing the data into a datatable inside a dataset, you could keep it simple and create a List(Of Joke).
This is for a console application:
Imports System.Net
Imports Newtonsoft.Json
Module Program
Class Joke
<JsonProperty("id")>
Property Id As Integer
<JsonProperty("type")>
Property Type As String
<JsonProperty("setup")>
Property Setup As String
<JsonProperty("punchline")>
Property Punchline As String
End Class
Sub Main(args As String())
Dim jokes As New List(Of Joke)
Using wc As New WebClient()
For i = 1 To 5
Dim jokeInfo = wc.DownloadString("https://official-joke-api.appspot.com/random_joke")
jokes.Add(JsonConvert.DeserializeObject(Of Joke)(jokeInfo))
Next
End Using
' Alternative which fetches ten jokes in one go - note the use of (Of List(Of Joke))
'Using wc As New WebClient()
' Dim jokeInfo = wc.DownloadString("https://official-joke-api.appspot.com/jokes/ten")
' jokes = JsonConvert.DeserializeObject(Of List(Of Joke))(jokeInfo)
'End Using
For Each jk In jokes
Console.WriteLine($"{jk.Setup}{vbCrLf}{jk.Punchline}{vbCrLf}")
Next
End Sub
End Module
The Using statement is needed because a WebClient should be disposed of after use to clear up system resources. (You could use the equivalent Try...Finally with wc.Dispose() instead.)
The JSON you showed is invalid. Datatable is expecting array of Object , so the JSON should look like below :
[{"id":130,"type":"general","setup":"test?","punchline":"test."}]

Need help to convert a class to XML and then a bytearray

I thought this would be an easy task but I seem to have gotten lost in a rabbit hole.
I am trying to convert a class to XML and then a byte array in order to send it as the content of a HTTPWebRequest for a WCF Restful webservice. My code will return the class as XML in the Byte Array but the format is incorrect. The XML looks like this:
<?xml version="1.0" encoding="utf-8"?><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><FirstName>Richard</FirstName><LastName>Cranium</LastName></Person>
I was attempting to use the OmitXmlDeclaration method thinking this would eliminate the extra declarations but it does not work with the xmltextwriter object and when I use the xmlwriterobject I can't determine how convert the outcome to a Byte array.
Here is my code:
Private Shared Function GenerateXMLPersonAsByte(strFirstName As String, strLastName As String) As Byte()
' This should serialize this to a byte array
Dim p As New Person()
p.FirstName = strFirstName
p.LastName = strLastName
' Want to use this with the xmlTextWriter but it does not support the property it is to be used with the XMLWriter instead
'Dim settings As XmlWriterSettings = New XmlWriterSettings()
'settings.OmitXmlDeclaration = True
'settings.ConformanceLevel = ConformanceLevel.Fragment
'settings.CloseOutput = False
' Create the XmlWriter object and write some content.
Dim mStream As New MemoryStream()
Dim ser As New XmlSerializer(GetType(Person))
Dim xmlTW As New XmlTextWriter(mStream, Encoding.UTF8)
ser.Serialize(xmlTW, p)
mStream = DirectCast(xmlTW.BaseStream, MemoryStream)
mStream.Close()
Return mStream.ToArray()
End Function
What must I do in order to get the XML with the correct opening tag?
or
How do I get the output from the XmlTextWriter object to a byte array?
I can't answer the whole question, but convert to string first
Dim myXmlString As String
Dim myStringWriter As New StringWriter()
Dim myXmlTextWriter As XmlTextWriter = New XmlTextWriter(myStringWriter)
'Write XML, and then flush the writer...
myXmlTextWriter.Flush()
'Return text from string writer...
myXmlString = myStringWriter.ToString()
'Close the Objects...
myStringWriter.Close()
myXmlTextWriter.Close()
then convert to byte using (sorry, C#, but you get the .NET call)
byte[] data = ASCIIEncoding.UTF8.GetBytes(myXmlString);

Error "Data at the root level is invalid" after transformation, while doing a LoadXML

I am trying to do some XSLT transformation, to convert an XML to XML, using the following lines of code. When i try to create an XMLDocument object from the transformed XML i am getting an error
Data at the root level is invalid. Line 1, position 1.
Dim outputXML As New XmlDocument
Dim stream As New MemoryStream
Dim writer As XmlTextWriter = New XmlTextWriter(stream, System.Text.UnicodeEncoding.UTF8)
Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
Dim transormer As XslCompiledTransform = New XslCompiledTransform()
transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
transormer.Transform(navigator, Nothing, writer)
Dim output As String = System.Text.UnicodeEncoding.UTF8.GetString(stream.ToArray())
outputXML.LoadXml(output)
Return outputXML
I could find a special character(square box), i persume this is causing the error. attached snapshot of the output xml. Can somebody please suggest ?
If you want to populate an XmlDocument as the result of an XSLT transformation then simply do
Dim resultDoc As New XmlDocument()
Using xw As XmlWriter = resultDoc.CreateNavigator().AppendChild()
Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
Dim transormer As XslCompiledTransform = New XslCompiledTransform()
transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
transormer.Transform(navigator, Nothing, xw)
xw.Close()
End Using
There is no need to use a MemoryStream. If you really think you need to use a MemoryStream then make sure you reset its Position to 0 before calling the Load method.

Visual Basic set User Agent with ReadXml

I'm trying to set the user agent for a request with XmlRead. I googled a lot about this and couldn't find the answer. Here is my chunk of code:
Dim RssData As DataSet
Dim Title As String
Dim Url As String
Dim Stream As String
Dim buffer As Integer
RssData = New DataSet()
RssData.ReadXml("http://localhost/user_agent.php")
buffer = 0
For Each RssRow As DataRow In RssData.Tables("entry").Rows
Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
Stream += Title & vbCrLf
Next
LinkLabel3.Text = Stream
For Each RssRow As DataRow In RssData.Tables("entry").Rows
Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
Url = RssRow.Item("url").ToString
LinkLabel3.Links.Add(buffer, Title.Length, Url)
buffer = buffer + Title.Length + 2
Next
The part of the code that actually performs the web request is buried pretty deep so you'd have to inherit a bunch of code to do what you asked for. Instead, let me suggest a different path, download the XML on your own with code that's easy to set that header, and then load that into the dataset. The WebClient class lets you set arbitrary headers and has a simple DownloadString method. Once you've got that you can wrap it in a MemoryStream and pass that into ReadXml(). (I couldn't find a way to read the XML as a string, that's why I was forced to read it as Stream.)
''//Will hold our downloaded XML
Dim MyXml As String
''//Create a webclient to download our XML
Using WC As New System.Net.WebClient()
''//Manually set the user agent header
WC.Headers.Add("user-agent", "your user agent here")
''//Download the XML
MyXml = WC.DownloadString("http://localhost/user_agent.php")
End Using
''//Create our dataset object
Dim RssData As New DataSet()
''//There is no direct method to load XML as a string (at least that I could find) so we will
''// convert it to a byte array and load it into a memory stream
Dim Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(MyXml)
Using MS As New System.IO.MemoryStream(Bytes)
''//Load the stream into the reader
RssData.ReadXml(MS)
End Using
''//Your code continues normally here

Infinite loop when Json serializing a Collection (VB ASP.NET)

I am trying to use a Web Service to return Json for a Collection of Users from a Database Table. I'm only new to .NET (< 1 week experience), and I don't want to use the UpdatePanel for AJAX. I have tried using the JavaScriptSerializer as well as Json.NET to serialize. Both cases seem to spawn an Infinite Loop.
What am I doing wrong? Is there a better way to do this? I appreciate any suggestions. Thanks.
Dim myUser As New HagarDB.Users
myUser.Read()
'Dim jsSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
'Dim sbUsers As New System.Text.StringBuilder
'jsSerializer.Serialize(myUser, sbUsers)
Dim json = JsonConvert.SerializeObject(myUser, Formatting.Indented)
Thanks to RPM1984 for suggesting DataContractJsonSerializer. Here is the working code:
Public Function GetUsers() As String
Dim myUser As New HagarDB.Users
Dim jsonSerializer As New DataContractJsonSerializer(GetType(HagarDB.Users))
Dim stream As New MemoryStream()
myUser.Read()
jsonSerializer.WriteObject(stream, myUser)
Dim json As String = Encoding.[Default].GetString(stream.ToArray())
stream.Close()
Return json
End Function