Deserialize XML string to class vb.net: Benefits and challenges
- masfoginberedi
- Aug 20, 2023
- 5 min read
Building a serialization for a class is simple enough following roughly thesame steps you would take to save the object in a database, as described in theprevious section. The class just concatenates the object's variable valuesinto a string. Later, it could parse the serialization string to restore theobject. To make an XML serialization, the class includes the proper tags.
Here's the cool trick: VB.NET's XmlSerializer class canserialize and deserialize your classes for you. XmlSerializer usesVB.NET's reflection tools to examine the class and figure out what it needsto do to serialize and deserialize it. If you later modify your class, theXmlSerializer automatically changes the way it serializes anddeserializes objects.
deserialize xml string to class vb.net
In the second approach you first deserialize XML data into a C# object and then serialize the C# object to JSON. If you wish to convert from JSON to XML similar process will be followed - JSON to C# object and C# object to XML. To follow this approach you can use .NET Core's XmlSerializer and JsonSerializer classes.
This code is quite simple and straightforward. It uses JsonSerializer class from System.Text.Json namespace. The Serialize() method of JsonSerializer accepts an object to be serialized and returns a JSON string. The JSON string is returned to the caller.
Inside, the code creates an XmlSerializer and StringReader objects. The XML string passed to the XmlToJson() method is fed to the StringReader. The StringReader is then supplied to the Deserialize() method of XmlSerializer. The Deserialize() method deserializes the XML data into an Employee object. The Employee object is then passed to EmployeeToJson() method to get its JSON equivalent. The JSON string is then returned to the caller.
We declare a MovieStats container class for our sample data sources. For now, it consists of an Xml property that holds information about the SquidGame movie in XML format. We aim to transform this into a JSON string.
In the first step, we deserialize the JSON to RootObject using the Deserialize method of the JsonSerializer class. This RootObject holds our SquidGame target object as a property. Subsequently, we serialize this to XML using the ObjectToXml helper method.
The XML serialization/deserialization of report definitions is achieved through the dedicated ReportXmlSerializer class. To illustrate how a report is serialized and deserialized, let us start with a simple dynamically generated class report definition:
The data types contained in an XML Schema are defined by the World Wide Webconsortium (www.w3.org). For many of these simple data types like intand decimal there is a corresponding data type inthe .NET Framework. However, some XML data types do not have a correspondingdata type in the .NET Framework (like the NMTOKEN data type). In this case, ifyou use xsd.exe to generate class definitions froman XML Schema, an appropriate attribute is applied to a member of type stringand its DataType property is set to the XML datatype name.
We could then create an instance of this class, set its properties and then throw it over to the PostObjectToURL() function, along with the URL endpoint of our destination API, and it will serialize it as an XML POST request. On the flip side the other site can then receive the post request, deserialize it (using the same Serializer class) into a matching object type and use it as a normal class instance. Here are the steps of how we could serialize our object using these methods.
Applications using custom mappings for aliases of scalar types, string or blob must provide converter between the custom type and the default type. The converter is a public class named BondTypeAliasConverter defining a pair of public static Convert methods for each type alias:
In the example above the Xml reader and writer are constructed directly from an instance of System.Stream. Underneath however they use System.Xml.XmlReader and System.Xml.XmlWriter which provide fast, non-cached, forward-only Xml parsing and generation on top of many different data readers and writers. For example to deserialize Xml payload from a string:
In the example above the JSON reader and writer are constructed directly from an instance of System.Stream. Alternatively they can be also constructed from System.IO.TextReader and System.IO.TextWriter. For example to deserialize JSON payload from a string:
As you can see we're talking about a simple static class filled with multiple "pairs" of related methods: the former one will serialize any object of typeT into a string, while the latter will deserialize it from the corresponding format. It's worth noting that the serialize methods can also be used as extension methods, assuming the class namespace is properly referenced wherever we want to use it. The class can be used as part of any C# class library or directly included in any Web Forms, Windows Forms, MVC, WebAPI, .NET Core or any other C#-based project type.
First we simply create a class that models our actual XML file. We use a bunch of attribute to specify how to read the doc, which namespace we are using, even what type of element we are trying to deserialize (e.g. An attribute, element or array).
In order to use the original XML data in our project, all we need to do is deserialize the XML file using the class we just generated. By creating an XML schema and adding it to a project, Visual Studio will create a strongly typed DataSet for you as well. Anyway, the deserialization code is shown below.
Further discussion is available via this reference.Below is an XML code sample that would be converted to a C# object.1. 2. 3. 4. 5. A class with a similar structure would be created in C# to convert the XML code sample.using System.Xml.Serialization;[XmlRoot(ElementName = "Company")]public class Company public Company() Employees = new List(); [XmlElement(ElementName = "Employee")] public List Employees get; set; public Employee this[string name] get return Employees.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)); public class Employee [XmlAttribute("name")] public string Name get; set; [XmlAttribute("age")] public string Age get; set; The final step to convert the XML object to C# is to use the System.Xml.Serialization.XmlSerializer function to serialize the object.public T DeserializeToObject(string filepath) where T : class System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T)); using (StreamReader sr = new StreamReader(filepath)) return (T)ser.Deserialize(sr); Use the Paste Special Feature of Visual Studio to Deserialize Xml to C# ObjectThis method requires using the Microsoft Visual Studio 2012 and above with .Net Framework 4.5 and above. The WCF workload for Visual Studio must also be installed.The content of the XML document must be copied to the clipboard.Add a new empty class to the project solution.Open the new class file.Click on the Edit button on the menu bar of the IDE.Select Paste Special from the dropdown.Click on Paste XML As Classes.To use the class generated by Visual Studio, create the Helpers class.
Below are the steps to follow to deserialize the XML to C# classes automatically:Type Developer Command Prompt into the search bar and click on it to open.Type cd C:\X to navigate to the XML file path.Remove line numbers and any unnecessary characters in the XML file.Type xsd test.XML to create an XSD file equivalent from the test.XML.A test.XSD file is created in the same file path.Type XSD /c test.XSD to create the C# classes equivalent to the XML file.A test.cs file is created, a C# class with an exact schema of the XML file.Output://------------------------------------------------------------------------------// // This code was generated by a tool.// Runtime Version:4.0.30319.42000//// Changes to this file may cause incorrect behavior and will be lost if// the code is regenerated.// //------------------------------------------------------------------------------using System.Xml.Serialization;//// This source code was auto-generated by xsd, Version=4.8.3928.0.///// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")][System.SerializableAttribute()][System.Diagnostics.DebuggerStepThroughAttribute()][System.ComponentModel.DesignerCategoryAttribute("code")][System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)][System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]public partial class Company private CompanyEmployee[] itemsField; /// [System.Xml.Serialization.XmlElementAttribute("Employee", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public CompanyEmployee[] Items get return this.itemsField; set this.itemsField = value; /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")][System.SerializableAttribute()][System.Diagnostics.DebuggerStepThroughAttribute()][System.ComponentModel.DesignerCategoryAttribute("code")][System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]public partial class CompanyEmployee private string nameField; private string ageField; /// [System.Xml.Serialization.XmlAttributeAttribute()] public string name get return this.nameField; set this.nameField = value; /// [System.Xml.Serialization.XmlAttributeAttribute()] public string age get return this.ageField; set this.ageField = value; Author: Abdullahi SalawudeenAbdullahi is a full-stack developer and technical writer with over 5 years of experience designing and implementing enterprise applications. He loves taking on new challenges and believes conceptual programming theories should be implemented in reality. 2ff7e9595c
Comments