Click here to Skip to main content
15,899,679 members
Everything / XmlSerializer

XmlSerializer

XmlSerializer

Great Reads

by Dirk Bahle
Tips & Tricks on De/Serializing object graphs with XML
by Shaun C Curtis
How to quickly generate code to handle XML files with an XSD definition
by Maciej Los
If you want to know the way you can serialize and deserialize custom class collection, this tip is for you.

Latest Articles

by Shaun C Curtis
How to quickly generate code to handle XML files with an XSD definition
by altomaltes
This code allows dumping and retrieval from a single variable to a complete tree of objects using both JSON and XML, in an unintrusive way, using tentative templates.
by Dirk Bahle
Tips & Tricks on De/Serializing object graphs with XML

All Articles

Sort by Title

XmlSerializer 

20 Jul 2022 by Jeff Huckins 2021
I have code that exists in both a .NET Framework 4.7.1 solution and in a .NET 5 solution. Although the serialization code works fine in .NET Framework 4.7.1, the constructor for the XmlSerializer throws a KeyNotFoundException on an enum from one...
19 Jun 2014 by Maciej Los
If you want to know the way you can serialize and deserialize custom class collection, this tip is for you.
24 Jun 2016 by mcondon013
Code that adds built-in serialization functionality to your classes in C#
8 May 2017 by Member 2127939
The code below currently works and loads XML into a class structure. This structure consists of a collection of items (items), each that have fixed properties and a collection that I use for a variable number of properties. Two things I want to do: 1) I want to change the list into something...
8 May 2017 by Richard Deeming
Assuming the elements in your XML file are actually cased correctly, and the missing closing elements are present, you just need to change the type of your KVPS property from: List> to List> You're currently using the built-in...
26 Nov 2014 by ToShX
Hey,I have the problem, that I have to serialize multiple objects of the same type to a xml-file with the XmlSerializer-Class. But I'm only able to create xml-files like this one here: A 0 0 ...
26 Nov 2014 by Sergey Alexandrovich Kryukov
How about not dealing with XML manually at all? The best XML serialization is implemented using the Data Contract:http://msdn.microsoft.com/en-us/library/ms733127%28v=vs.110%29.aspx[^].Please see my past answers where I advocate this approach:How can I utilize XML File streamwriter and...
26 Nov 2014 by Joezer BH
Should be fairly simple.Try creating the XmlSerializer with the constructor that also takes XmlRootAttribute// Fix this line of code, use the costructor that follows : XmlSerializer(Type, XmlRootAttribute)XmlSerializer xmlSerializer = new XmlSerializer(typeof(TimeProjects));// try...
26 Nov 2014 by Er. Dinesh Sharma
Hi Please try this Codepublic class MakeSer { public MakeSer() { TimeProject tm = new TimeProject(); Projects[] proj = new Projects[2]; proj[0] = new Projects { Comment = "X", name = "Y", TimeToday = "40", TimeTotal = "10" }; ...
28 Oct 2014 by Hein_vdw
I have created a rest service and it is working perfectly with my get operation, but i am trying to implement a POST, but when the xml data reaches the service it looks like this (missing half the objects and priority changes to 0 instead of 8888) :
28 Oct 2014 by Hein_vdw
Ended up using a DataContractSerializer instead of a xmldocument from the clientside
23 Apr 2015 by Sethi1978
I made a self-hosted web service in c# and everything works fine.I work on this base Object class (DevExpress XPO): [Persistent(System.StatusTable)] public class XPStatusTable : XPBaseObject { private short fIDTable; [Key(true)] public short...
13 Jul 2015 by Member 11684783
Dear Folk,i got a fine working XMLSerializer for a sophisticated List of 3D model with many different elements. Now i want to serialize another List beside of that, that only saves few Elements of it. I just tried to bar some of them out with [XMLIgnore] but this causes problems in my...
22 Dec 2015 by snziv
I have this query, can we do CRUD operation on XML using Serialization and Deserialization (using system.xml.serialization library )I know it can be done using other libraries like xmldocument,XMLWriter but just curious to know whether is there any way that we can perform CRUD using...
17 Mar 2014 by KUMAR619
I can use Xml writer to write any Xml document but can we write again using Xml Writer.If so how to do this
29 Apr 2015 by Member 11605590
Hi all,I am creating an XML document from a schema. I used xsd.exe to create a class file from the xsd. I have a datatable that I am using to write the xml with. Below is a sample with only first name and surname. The problem is that it only writes the last item from the datatable. What...
6 Feb 2014 by mibetty
I´m studying XML and so far appeared text problems and i think i get it.But now i have this exercise and I did not realize what I have to do.The exercise asks to write the xml document for this image but only the dynamic content.Dynamic, we only have spotlight Videos and the rightVideos,...
20 May 2014 by normalsoft
please comment about XML serialization.
12 May 2014 by dan!sh
You will need to create a Serializable class that represents this XML format and then use XMLSerializer class and its methods to get the object.You can use XSD.exe to create class that will represent this XML.
20 May 2014 by Maciej Los
Start here: Introducing XML Serialization[^] and follow the links on your left ;)
14 Feb 2015 by Ifat Chitin Morrison
This tip shows the differences in XML serialization when a serializable class has a combination of [XmlElement] and [XmlText].
24 Feb 2017 by Member 11748288
hi i have two class foo and wrappersfoo is my original class and i create a list from foo class and wrappers class decorate with [serializable] and [xmlelement(ElementName=)]this is my foo class public class foo { public string Name { get; set; } public...
24 Feb 2017 by Graeme_Grant
What you want doesn't seem to be too standard, XML explicitly disallows numbers (and some other things) as the first character of an element name:NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | ...
14 Mar 2017 by Amien90
using (StreamWriter file = File.CreateText(@"c:\test\source.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, eList); }I use this to write my JSON Object to a json file. But is it easy with some...
14 Mar 2017 by Graeme_Grant
The answer is yes and no. It depends on how the data is to be serialized.I have two Converter classes, one for JSON & one for XML. Both are called the same way, so easy to switch. I'll post both below. The XML version has additional information that should be self-explanatory.JSON...
14 Mar 2017 by F-ES Sitecore
System.Xml.Serialization.XmlSe...
11 Sep 2019 by Krishna Chaitanya Bezawada (Chaitu)
I have a Web service, which returns the Response in XML. I am getting an error while reading the response if the response have empty fields. I have tried different code for XML deserialization, but none of them is working. I have below deserialization code written. I have tried this one and it...
11 Sep 2019 by dnxit
I don't know how you're parsing the xml, what I can see is your mapping class does not seem to be in according with your swagger, try with this class using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Xml2CSharp { [XmlRoot(ElementName="item")] public...
26 Mar 2015 by Member 11491784
27 Mar 2015 by Mario Z
Hi, well I see you have successfully retrieved the desired XmlNode. All that is left for you is to retrieve the required attribute from that node.So something like this:Dim bookAmoount = Book.Attributes("amoount").ValueAlso just in case you're interested you can simplify your code with...
10 Jun 2014 by Harshad Gharote
I have this code which converts an object to xmldocument but while doing that i get this error The code is which returns the xmldocument is below :public static XmlDocument ToXmlDocument(this MyClass myclass) { var result = new XmlDocument(); var xml =...
10 Jun 2014 by Kornfeld Eliyahu Peter
I can't understand why you are using some 3rd party extension to serialize an object to XML, but if this is a requirement then go and ask the 3rd party for support!If you can choose your way, than you be better with the simple .NET way of XML serialization (and deserialization)...Start...
12 Jul 2016 by ebie147
hi guys so i got a datagridview that has a dataset that is linked to a xml file,I got to display the data in the datagridview but what i want to do now is take out rows that has certain values,this is my code'Load Creditors data Dim CPADataset As New DataSet Dim...
26 May 2019 by altomaltes
This code allows dumping and retrieval from a single variable to a complete tree of objects using both JSON and XML, in an unintrusive way, using tentative templates.
29 Mar 2014 by Sergey Alexandrovich Kryukov
This is the XML Schema file. Please see: http://msdn.microsoft.com/en-us/library/04x694fe%28v=vs.110%29.aspx[^].—SA
27 Feb 2018 by Graeme_Grant
Firstly, you have an error in the XML data sample on line# 443. I would map classes to the XML data and convert. But it you want to manually read the xml data, then you could do something like this: var doc = XDocument.Parse(rawXml); var products = doc.Descendants() ...
20 Apr 2016 by sahmed3
Hi i'm getting the xml values as null kinldy help.public logistics GetGeneralInfo(int StoreId) { var storeInfoWebService = new UATStoreReportServiceReference.oraclemdb1SoapClient("oraclemdb1Soap"); var logisticsInfoFromService =...
17 Apr 2016 by Patrice T
The problem may be that your XML file is not an XML file.Otherwise, using the debugger will show you exactly what is going on.
17 Apr 2016 by Sergey Alexandrovich Kryukov
The structure of your XML shows that it's schema is really a bad idea. It's pretty much plain home-baked text inside XML.[EDIT]Wait a minute… This is not XML file at all. It's not even well-formed; ppolymorphe brought it to my attention in Solution 1. Well, you know… there...
17 Apr 2016 by saraswathi
May be the conversion from the xml to the object is not happening properly. Do you have access to the logistics class? Can you check how the Deserializer deserializes your freightrate and OffshreDelivery properties from the xml to object or what ever type they are? by that i mean what is the...
20 Apr 2016 by sahmed3
I have updated the code as below public ActionResult GetLogisticsReport(int StoreId) { StoreId = 00316; try { XmlDocument xmlDoc = new XmlDocument(); string LogisticsReportResponseXml =...
2 Mar 2017 by Praveen Behera
Hello guys,This is my first time in the site, so possibly i am unsure how to ask questions. Still here it is -I have an excel file containing xml files in oledb object form.What i need is, how can i get the label and file path of that xml file stored in oledb using C#.Note:...
29 Mar 2022 by enoughIsenough
I have a XML file and it goes as below and I'm trying to bring out the Node Attribute value from Node Value A
22 Mar 2022 by unipam
Maybe if you try something like this: public string GetSelectValue(string pinValue) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Server.MapPath("load.xml")); XmlElement root = xmlDoc.DocumentElement; XmlNodeList nodes =...
29 Mar 2022 by Richard Deeming
Seems simple enough using LINQ to XML[^]: // Values to find: string pin0 = " value0 ", pin1 = null, pin2 = " value2 ", pin3 = null; XDocument document = XDocument.Load("load.xml"); var select = doc.Descendants("Select").Select(s => new { ...
4 Feb 2018 by KumarAbhishekJaiswal
Dear All I generated an XML from a Simulink (Matlab 2017b) model. The idea is to get the Model Properties from the XML into Class Objects (I am using C# .Net 4.5). Below in the generated XML.
4 Feb 2018 by Maciej Los
KumarAbhishekJaiswal - Professional Profile[^] wrote: it does not look like any traditional XML You're wrong. This xml has proper form. See: XML attributes[^]. I did exactly what is described here: c# - How to Deserialize XML document - Stack Overflow[^] and the classes generated by xsd.exe...
17 Dec 2019 by Tshumore
I have a console program that reads a XML File and prints some selected value in the console. When i run the program i get an exception Inner Exception 1: InvalidOperationException: was not expected. for the header tag...
16 Dec 2019 by #realJSOP
Put a try/catch block around your code so you can see where the exception is being thrown. BTW, it's an Invalid Operation exception.
20 Dec 2019 by Richard Deeming
There's a syntax error in your XML: the element is self-closing, but it also has a closing tag. Quote: The 'EXPORT_HEADER' start tag on line 2 position 2 does not match the end tag of 'TRANSACTION'. Line 4, position 5. Once that's fixed, your "What I have tried" code works to...
7 May 2015 by Joshua Masa
Hi,I have a serialized XML that is converted to Json (Not sure if I said that right). It did the serialization successfully but I am going to be passing this Json to a web api to be posted via postman. Unfortunately, I need to get rid of root from the produced...
7 May 2015 by Sergey Alexandrovich Kryukov
This is nonsense. XML document, by definition, has one and only one root. If you remove the root, the next level of hierarchy can be one element of more than one. If there is only one element, removing root will give you valid XML (or at least well-formed). This is not the case in your example,...
7 May 2015 by Maciej Los
If you want to skip root element and get only child nodes, use this:var invoices = xdoc.Root.Elements();Now, you can "convert" it into json object.Note, that using your code you'll get something like this:{"ExtSerial":"KDI2015050501"},{"Date":"02/01/2015"},...but...
4 Aug 2014 by Anshumaan Chaturvedi
I have an XML file consisting of an element "Settings". All the rest of the elements are getting populated in DataTable but settings.While reading in the XML file this is the reference code i implemented.But the breakpoint is not hitting the "Settings" case.foreach (DataRow drow in...
25 Jun 2018 by James McCullough
I have a situation where a client requires the " and ' characters to be escaped in XML explicitly into " and ' respectively. XMLSerializer was written (apparently) with the idea in mind that since these are not strictly required in most circumstances, they would ignore them. Surely I'm not the...
25 Jun 2018 by Kornfeld Eliyahu Peter
I do not understand what do you mean by 'escape' (like in C# string \n\r?), but XmlSerializer converts special characters to it's entity value automatically, otherwise it would not be a valid XML... UPDATE You have to understand (and explain the customer) that quotes and double-quotes are...
25 Jun 2018 by Dave Kreskowiak
Like Peter up in Solution 1 said, you're going to have to write your own custom serializer to handle the customer required changes. Just Google for "C# custom xml serializer" and you'll find plenty of examples.
30 Mar 2015 by Member 10420430
How to change the elements name depending on condition.e.g Class Section{[XmlAttribute(AttributeName = "name")]public string Name{get;set;}[XmlElement(ElementName = "question")]public ListQuestion{get;set;}} Class Question{public int...
17 Mar 2014 by KUMAR619
I want to check whether all the XML element in the XML file are located in ascending order or not.I want to check them through an attribute called ID.Is there any way to do soHow to do so.string[] g = new string[count]; for (int i = 0; i
17 Mar 2014 by Vedat Ozan Oner
you can make your array 'a' sorted. List a = g.ToList().Select(i=>int.Parse(i)).OrderBy(i=>i);List missings=new List();int idx=0; // a indexfor(int i=0; i
8 Nov 2018 by Somu M
- 01-01-2018 Payments SOURCE ...
11 Sep 2014 by Naveen Singh
i have an asp.net application ...*i have to fetch xml which includes xml header
3 Oct 2014 by BrooksV2
One method for reading and parsing XML data is to use System.Xml.XmlTextReader(). This will allow you to extract out exactly what you need from the XML.This code example will demonstrate the basics of finding Elements and attributes. Since your situation doesn't require retrieving Attribute...
21 Jul 2014 by Riccardo Macaluso
Hi guys! I have to ask you help for XML serialization.I have to deserialize this XML document (a piece of electronic invoice): IT 12345689 ...
21 Jul 2014 by Maciej Los
Here, on CP site, you'll find several articles about serialization and deserialization of XML. Please, use SearchBox[^] on the right-top corner of this site, for example: A Complete Sample of Custom Class Collection Serialization and Deserialization[^]
24 Feb 2016 by satrio_budidharmawan
Hi, I am newly working with XML files with C#, currently I am facing a problem about editing a specific value from XML file.Let's say I have this XML file (plist.xml) : Dominic Crossroad Android ...
24 Feb 2016 by Manas_Kumar
Try with below code:string xmlData = @" Dominic Crossroad Android 1522 dominicroad 1.0.0, 1.2.0i, 2.0.0j
28 Apr 2015 by dinesh_redhawk
I have to parse the data from a very big xml file with lot of repeatetive elements and child nodes. I could have used the GetElementsbyTagName but that will be a very lengthy and complex solution w.r.t this xml file.I think the best method would be xml serialization and deserialization...
28 Apr 2015 by Leo Chapiro
Basically take a look at this answer:Use XML reader instead of XML dom. XML dom stores the whole file in memory which is totally useless: XmlReader ClassYour second question:Quote:How to use/access "private ATXARPACKAGE[] aRPACKAGESField" Why have you made this variable...
28 Apr 2015 by Mehdi Gholam
Start here : http://stackoverflow.com/questions/15772031/how-to-parse-very-huge-xml-files-in-c[^]https://msdn.microsoft.com/en-us/library/bb387013.aspx[^]
16 Nov 2015 by Raseeth90
public string XmlSerializer(Object item){ StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(builder,...
17 Nov 2015 by Henrik Jonsson
One option is to perform some post-processing of the output using regular expressions:First define the following Regex to find the empty tags:static Regex emptyElementRegex = new Regex(@"");Then process your output to replace all matching occurrences:var result =...
7 Mar 2014 by Divakar Raj M
I generated a XML Serialization using the following C# codepublic class Program { static void Main(string[] args) { AddressDirectory addr = new AddressDirectory(); Address A1 = new Address(); A1.City = "Chennai"; ...
7 Mar 2014 by Vedat Ozan Oner
I have changed your code a little bit:using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml.Serialization;namespace Test_XmlSerialize2{ public class Program { static...
12 Dec 2017 by vksvpp
Hi, sample code is, In this I need to remove xsd namespace. Required: I...
12 Dec 2017 by Leo Chapiro
You can simple split the XML string by blank and remove the part with "xmlns:xsd": string strXml = ""; string[] ar = strXml.Split(' '); string strResult = string.Empty;...
30 Jul 2014 by Shyam Kishor Mishra
This is an XML SOAP web Service Response, i want to store all the values in database and again fetch to the webpage. but this XML is not able to pass through DataSet shows Error The table (item) cannot be the child table to itself in nested relations.Please help. or any other way to show...
20 Mar 2014 by KUMAR619
I am having an XL file having several nodes of same name.I want to select these nodes one by one for further purpose.
20 Mar 2014 by ZurdoDev
I would use the XDocument or you could also use the XmlDocument. The XDocument is newer and supports Linq.http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument_methods(v=vs.110).aspx[^]You can use Elements() or Descendants() etc.
25 May 2015 by Mohammad Adi
"here url xml"**And it's my controller** [HttpGet] public JsonResult getXMLrequest() { var response = new HttpResponseMessage(); var urlDJP = Request.QueryString["urldjp"]; var data = new VatInRecieveModels(); ...
20 Apr 2015 by Lalyka
I want to send a http request from client to local server and on the server I made a query with Linq that returns data in xml I also have .xsd file and a .cs file enerated from my xsd file that I want to validate my xml with. I have several questions:how can I validate xml with c# generated...
20 Apr 2015 by Maciej Los
Wikkipedia wrote:XML validation is the process of checking a document written in XML (eXtensible Markup Language) to confirm that it is both well-formed and also "valid" in that it follows a defined structure. A well-formed document follows the basic syntactic rules of XML, which are the same...
26 Mar 2015 by Sergey Alexandrovich Kryukov
Parse it is appropriate data structure first, or use XML serialization, or use LINQ To XML.—SA
13 Mar 2017 by Pragya Nagwanshi
I have to create class of these xml file.Label Label1 label 20 30 35 13 True True...
13 Mar 2017 by CHill60
This CP article should help you along: XML Serialization and Deserialization: Part-2[^]
12 Aug 2014 by angiangi
I'm trying to get nested hierarchy data from large XML file and show it in a tree structure in MVC application.I need to considerate performance issue as well, because I'm using a large xml file.I started with parsing the xml with XmlReader and now i thinking to use XmlSerializer, what do...
13 Aug 2014 by Yogesh Kumar Tyagi
view this link for mvc tree view How to Create TreeView in MVC3[^]i think it will help you.Build a custom MVC Tree Control by using jsTree[^]
28 Oct 2015 by sunsuhesh
I have three classes: person, address and phone. A person can have multiple addresses and each address has phone numbers. Here how to initialize and assign values multiple address and phone number. Below is my class model.public class Person{ public string Name { get; set; } ...
28 Oct 2015 by Sergey Alexandrovich Kryukov
Here is my advice: through out this problematic XmlSerialize. Use much better Data Contract with DataContractSerialize — much easier to use, fully non-intrusive and data-agnostic, can work with arbitrary data model, not necessarily a tree, and so on. Please...
29 Oct 2015 by BillWoodruff
Quote: how to initialize and assign values multiple address and phone number.There are several ways you can initialize/assign to whatever Collection data-structure you select to hold the multiple values. Here's an example that reflects the way I like to work:public enum PhoneType{ ...
29 Oct 2015 by Maciej Los
I'd suggest to read:XML Serialization and Deserialization: Part-1[^]XML Serialization and Deserialization: Part-2[^]A Complete Sample of Custom Class Collection Serialization and Deserialization[^]
10 Sep 2017 by TabZhang
Dear I am quite new for C#,I'm looking for help with the following questions. I am Plan to build one adaptable test platform with C# to achieve the following features,it just like NI-Teststand, but quite support .Net Only. This is dummy Test Tree, Each Step will use Reflection Call .Net...
10 Sep 2017 by Graeme_Grant
XML is not the most efficient at passing data between two processes. Rather than specifying only one way of doing this, here is a Google Search that will give you a few different solutions: c# passing between processes - Google Search[^]
10 Sep 2017 by CPallini
Quote: it without create new instance to improve efficiency. Do you really think you need that? I strongly doubt you are going to observe a performance improvement.
22 Dec 2017 by Dirk Bahle
Tips & Tricks on De/Serializing object graphs with XML
1 Dec 2020 by Shaun C Curtis
How to quickly generate code to handle XML files with an XSD definition