How to read XML file using XmlSerializer C# [duplicate] - c#

This question already has an answer here:
Deserialization of xml file by using XmlArray?
(1 answer)
Closed 6 years ago.
I have a problem when I want to read XML file by using XmlSerializer.
My xml file like follow :
<?xml version="1.0" encoding="utf-8"?>
<contents>
<section id="1">
<element1>2</element1>
<element2>1</element2>
<idx>1</idx>
<idx>2</idx>
<idx>3</idx>
</section>
<section id="2">
<element1>2</element1>
<element2>1</element2>
</section>
<section id="3"/>
</contents>
Here are the classes:
[Serializable()]
public class section
{
[XmlAttribute("id")]
public string id { get; set; }
[XmlElement("element1")]
public int element1 { get; set; }
[XmlElement("element2")]
public int element2 { get; set; }
[XmlElement("idx")]
public int[] idx { get; set; }
}
[Serializable()]
[XmlRoot("contents")]
public class contents
{
[XmlArray("section")]
[XmlArrayItem("section", typeof(section))]
public section[] section { get; set; }
}
The Deserialize function:
XmlSerializer serializer = new XmlSerializer(typeof(contents));
FileStream fs = new FileStream(path, FileMode.Open);
XmlReader reader = XmlReader.Create(fs);
contents i;
i = (contents)serializer.Deserialize(reader);
fs.Close();
foreach (section p in i.section)
{
Console.WriteLine(p.element1);
}
Why it doesn't work?
I had reference https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx but it seem not useful.
Please help me!!!!!

Try this...
Usings...
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
Classes...(created from your XML using http://xmltocsharp.azurewebsites.net/)
[XmlRoot(ElementName = "section")]
public class Section
{
[XmlElement(ElementName = "element1")]
public string Element1 { get; set; }
[XmlElement(ElementName = "element2")]
public string Element2 { get; set; }
[XmlElement(ElementName = "idx")]
public List<string> Idx { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "contents")]
public class Contents
{
[XmlElement(ElementName = "section")]
public List<Section> Section { get; set; }
}
Code...
Contents dezerializedXML = new Contents();
// Deserialize to object
XmlSerializer serializer = new XmlSerializer(typeof(Contents));
using (FileStream stream = File.OpenRead(#"xml.xml"))
{
dezerializedXML = (Contents)serializer.Deserialize(stream);
} // Put a break-point here, then mouse-over dezerializedXML
I put your XML in a file (xml.xml) and read it from there....

Related

There is an error in XML document (2, 2) when desearlizing xml to c# object

XML
<?xml version="1.0" encoding="UTF-8"?>
<orgc:Organizations xmlns:orgc="urn:workday.com/connector/orgs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<orgc:Organization>
<orgc:Organization_ID>SR1Code34</orgc:Organization_ID>
<orgc:Organization_Code>SR1Code34</orgc:Organization_Code>
<orgc:Organization_Type>Cost_Center_Hierarchy</orgc:Organization_Type>
<orgc:Organization_Name>LTL Services</orgc:Organization_Name>
<orgc:Organization_Description>LTL Services</orgc:Organization_Description>
<orgc:Organization_Subtype>ORGANIZATION_SUBTYPE-3-20</orgc:Organization_Subtype>
<orgc:Inactive>false</orgc:Inactive>
<orgc:Superior_Organization>DL2Code11</orgc:Superior_Organization>
</orgc:Organization>
<orgc:Organization>
<orgc:Organization_ID>SR1Code35</orgc:Organization_ID>
<orgc:Organization_Code>SR1Code35</orgc:Organization_Code>
<orgc:Organization_Type>Cost_Center_Hierarchy</orgc:Organization_Type>
<orgc:Organization_Name>Consolidation</orgc:Organization_Name>
<orgc:Organization_Description>Consolidation</orgc:Organization_Description>
<orgc:Organization_Subtype>ORGANIZATION_SUBTYPE-3-20</orgc:Organization_Subtype>
<orgc:Inactive>false</orgc:Inactive>
<orgc:Superior_Organization>DL2Code11</orgc:Superior_Organization>
</orgc:Organization>
</orgc:Organizations>
Class
[XmlRoot(ElementName = "Organizations", Namespace = "urn: workday.com/connector/orgs", IsNullable = true )]
public class CostCenterHierarchy
{
[XmlElement("orgc:Organization_ID")]
public string CostCenterHierarchyId { get; set; }
[XmlElement("orgc:Organization_Code")]
public string Code { get; set; }
[XmlElement("orgc:Organization_Name")]
public string Name { get; set; }
[XmlElement("orgc:Organization_Description")]
public string Description { get; set; }
[XmlElement("orgc:Organization_Subtype")]
public string Subtype { get; set; }
[XmlElement("orgc:Superior_Organization")]
public string ParentHierarchyId { get; set; }
}
Method to deseralize xml to c# class
private List<CostCenterHierarchy> ProcessCostCenterHierarchy(string filePath)
{
var costCenterHierarchyList = new List<CostCenterHierarchy>();
//var costCenterHierarchy = new CostCenterHierarchy();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<CostCenterHierarchy>));
using (var reader = XmlReader.Create(filePath))
{
var test = xmlSerializer.Deserialize(reader);
}
return costCenterHierarchyList;
}
Error Message
Message = "There is an error in XML document (2, 2)."
InnerException = {"<Organizations xmlns='urn:workday.com/connector/orgs'> was not expected."}
I'm not sure where I am going wrong. Seems like it should be pretty easy but I've played around with this and keep getting the same error message. Any help would be much appreciated.
The code below works. You have an array and serialization doesn't like a list as the type. The Url "urn:workday.com/connector/orgs" the serializaer doesn't like and had to replace the "urn:" with "http://workday.com/connector/orgs".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Organizations));
Organizations organizations = (Organizations)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "Organizations", Namespace = "http://workday.com/connector/orgs")]
public class Organizations
{
[XmlElement(ElementName = "Organization", Namespace = "http://workday.com/connector/orgs")]
public List<CostCenterHierarchy> organizations { get; set; }
}
public class CostCenterHierarchy
{
[XmlElement("Organization_ID")]
public string CostCenterHierarchyId { get; set; }
[XmlElement("Organization_Code")]
public string Code { get; set; }
[XmlElement("Organization_Name")]
public string Name { get; set; }
[XmlElement("Organization_Description")]
public string Description { get; set; }
[XmlElement("Organization_Subtype")]
public string Subtype { get; set; }
[XmlElement("Superior_Organization")]
public string ParentHierarchyId { get; set; }
}
}

How to de-serialise a list with multiple xsi:type

I'm using the XmlSerializer in System.Xml.Serialization.
I have a list (or two lists really) separated by xsi:type.
<?xml version="1.0" encoding="utf-8"?>
<ButikerOmbud xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Info>
<Meddelande>blah blah</Meddelande>
</Info>
<ButikOmbud xsi:type="StoreAssortmentViewModel">
<Typ>Butik</Typ><Nr>2515</Nr>
</ButikOmbud>
<ButikOmbud xsi:type="StoreAssortmentViewModel">
<Typ>Butik</Typ><Nr>2516</Nr>
</ButikOmbud>
<ButikOmbud xsi:type="AgentAssortmentViewModel">
<Typ>Ombud</Typ><Nr>011703-91A</Nr>
</ButikOmbud>
<ButikOmbud xsi:type="AgentAssortmentViewModel">
<Typ>Ombud</Typ><Nr>011703-92B</Nr>
</ButikOmbud>
</ButikerOmbud>
I've created some classes that map to this:
[XmlRoot(ElementName = "ButikerOmbud")]
public class ButiksCollection
{
[XmlElement(ElementName = "Info")]
public Info Info { get; set; }
[XmlElement(ElementName = "ButikOmbud")]
public List<Butik> Butiker { get; set; }
}
[XmlRoot(ElementName = "ButikOmbud")]
[XmlType(TypeName = "StoreAssortmentViewModel")]
public class Butik
{
[XmlElement(ElementName = "Typ")]
public string Typ { get; set; }
[XmlElement(ElementName = "Nr")]
public int Nr { get; set; }
}
and then I'll do this
(ButiksCollection)(new XmlSerializer(typeof(ButiksCollection)).Deserialize(memoryStream));
This should work if only the StoreAssortmentViewModel existed. But given that there exists AgentAssortmentViewModel under the same node. I'm not sure how I should de-serialise this. I'm assuming there should be another collection List<Butik> Agents on ButiksCollection.
The only attribute I've found that seems to map to xsi:type is applied to classes, which I don't think is what I want here
How do I arrange and attribute my classes so this will de-serialize?
Here's all that on dotnetfiddle: https://dotnetfiddle.net/vmT4SK
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(ButiksCollection));
ButiksCollection butik = (ButiksCollection)serializer.Deserialize(reader);
List<StoreAssortmentViewModel> storeAssortments = butik.Butiker.Where(x => x.GetType() == typeof(StoreAssortmentViewModel)).Select(x => (StoreAssortmentViewModel)x).ToList();
List<AgentAssortmentViewModel> agentAssortments = butik.Butiker.Where(x => x.GetType() == typeof(AgentAssortmentViewModel)).Select(x => (AgentAssortmentViewModel)x).ToList();
}
}
[XmlRoot(ElementName = "ButikerOmbud")]
public class ButiksCollection
{
[XmlElement(ElementName = "Info")]
public Info Info { get; set; }
[XmlElement(ElementName = "ButikOmbud")]
public List<Butik> Butiker { get; set; }
}
[XmlRoot(ElementName = "ButikOmbud")]
[XmlInclude(typeof(StoreAssortmentViewModel))]
[XmlInclude(typeof(AgentAssortmentViewModel))]
public class Butik
{
[XmlElement(ElementName = "Typ")]
public string Typ { get; set; }
[XmlElement(ElementName = "Nr")]
public string Nr { get; set; }
}
public class Info
{
public string Meddelande { get; set; }
}
public class StoreAssortmentViewModel : Butik
{
}
public class AgentAssortmentViewModel : Butik
{
}
}

Need help to deserialize XML data

I am trying to deserialize the below XML using C#
<?xml version="1.0" encoding="utf-8"?>
<Invoice>
<Samples>
<Sample>
<AccountId>1e547ae6-9a6d-d18f-958b-22000b83a845</AccountId>
<AccountNumber>55761598808</AccountNumber>
</Sample>
<Sample>
<AccountId>1e547ae6-9a6d-d18f-958b-22000b83a845</AccountId>
<AccountNumber>55761598808</AccountNumber>
</Sample>
</Samples>
</Invoice>
Here are the classes that I have defined to deserialize
[DataContract(Name = "Sample")]
public class Sample
{
[DataMember(Name = "AccountId")]
public string AccountId { get; set; }
[DataMember(Name = "AccountNumber")]
public string AccountNumber { get; set; }
}
[DataContract(Name = "Samples")]
public class Samples
{
[DataMember(Name = "Sample")]
public List<Sample> Sample { get; set; }
}
[DataContract(Name = "Invoice")]
public class Invoice
{
[DataMember(Name = "Samples")]
public Samples Samples { get; set; }
}
The corresponding test case to deserialize is as follows
public void SampleXmlTest()
{
dynamic env = SUT.GetEnvironment();
string dbConnStrUrjanet = (string)env.AvidUtility.UrjanetDB;
XmlSerializer deserializer = new XmlSerializer(typeof(CommonAvidXmlDto.Invoice));
TextReader reader = new StreamReader(#"C:\Users\SJuluru\Desktop\Sample XML\Samplexml.xml");
Object obj = deserializer.Deserialize(reader);
CommonAvidXmlDto.Invoice XmlData4 = (CommonAvidXmlDto.Invoice)obj;
After running the test case debug mode, XmlData4 has null without having the XML data. Kindly help me how to modify this code to work.
DataContract and DataMember are attribute of DataContractSerializer so you shoud replace your serializer msdn or use XmlSerializer's attributes (XmlRoot, XmlElement etc)
Change deserialize classes:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace ConsoleApp4
{
[XmlRoot(ElementName = "Sample")]
public class Sample
{
[XmlElement(ElementName = "AccountId")]
public string AccountId { get; set; }
[XmlElement(ElementName = "AccountNumber")]
public string AccountNumber { get; set; }
}
[XmlRoot(ElementName = "Samples")]
public class Samples
{
[XmlElement(ElementName = "Sample")]
public List<Sample> Sample { get; set; }
}
[XmlRoot(ElementName = "Invoice")]
public class Invoice
{
[XmlElement(ElementName = "Samples")]
public Samples Samples { get; set; }
}
}
Use below method for deserialize:
private static Invoice LoadInvoice(string fileName)
{
var serializer = new XmlSerializer(typeof(Invoice));
if (!File.Exists(fileName))
{
return null;
}
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
return (Invoice)serializer.Deserialize(fs);
}
}
Result:

deserialize xml into inherited classes from base class

I have the following xml structure:
<Root1>
<name>Name1</name>
<company>Comp1</company>
<url>site.com</url>
<elements>
<element id="12" type="1">
<url>site1.com</url>
<price>15000</price>
...
<manufacturer_warranty>true</manufacturer_warranty>
<country_of_origin>Япония</country_of_origin>
</element>
<element id="13" type="2">
<url>site2.com</url>
<price>100</price>
...
<language>lg</language>
<binding>123</binding>
</element>
</elements>
</Root1>
I need to deserialize this xml into an object. You can see the element contains some equals field: url and price.
I would like to move these fields into a parent class and then inherit this class from other classes.
I created the class Root1:
namespace app1
{
[Serializable]
public class Root1
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("company")]
public string Company { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("elements")]
public List<Element> ElementList { get; set; }
}
}
and then I created base class for Element:
[Serializable]
public class Element
{
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("price")]
public string Price { get; set; }
}
and then I inherited this class from other classes:
[Serializable]
public class Element1 : Element
{
[XmlElement("manufacturer_warranty")]
public string mw { get; set; }
[XmlElement("country_of_origin")]
public string co { get; set; }
}
[Serializable]
public class Element2 : Element
{
[XmlElement("language")]
public string lg { get; set; }
[XmlElement("binding")]
public string bind { get; set; }
}
When I deserialize this xml to object Root1 I get the object - it is ok.
But the List of Elements contains only Element objects not Element1 and Element2 objects.
How I do deserialize this xml so list of Elements contains Element1 and Element2 objects?
#netwer It is not working for you because the code suggested above generates the xml (below) that does not match with the one you use for deserialization (see how it specifies derived types in for element).
<?xml version="1.0" encoding="utf-8"?>
<Root1>
<name>Name1</name>
<company>Comp1</company>
<url>site.com</url>
<elements>
<element d3p1:type="Element1" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">
<url>site1.com</url>
<price>15000</price>
<manufacturer_warranty>true</manufacturer_warranty>
<country_of_origin>Япония</country_of_origin>
</element>
<element d3p1:type="Element2" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">
<url>site2.com</url>
<price>100</price>
<language>lg</language>
<binding>123</binding>
</element>
</elements>
</Root1>
So you will either have to match this format with source xml (change code or API that returns this xml data) or take another approach. Even if you manage to do with former one you have to find a way to access Element1 or Element2 specific properties.
newRoot1.Elements.ElementList[i] will always let you access only price and url since your list is of Element type. Although run time type of ElementList[i] will be Element1 or Element2, how will you detect that?
Here I suggest alternative approach. Irrespective of whether your application (client) generates this xml or the server which returns it on hitting API, you should be able to gather information on all the fields applicable to an 'element' object. If it is your code you know it already, if it is an API there must be a document for it. This way you only have to create one 'Element' (no derived classes) and put proper checks (mostly string.IsNullOrEmpty()) before accessing Element class property values in your code. Only the properties that are present in your xml 'element' element will be considered rest will be set to NULL for that instance.
[Serializable]
public class Element
{
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("price")]
public string Price { get; set; }
[XmlElement("manufacturer_warranty")]
public string mw { get; set; }
[XmlElement("country_of_origin")]
public string co { get; set; }
[XmlElement("language")]
public string lg { get; set; }
[XmlElement("binding")]
public string bind { get; set; }
}
I think you should use XmlIncludeAttribute like this:
[XmlInclude(typeof(Element1))]
public class Element
{
}
Here is xml and code. I like to first serialize with test data, then deserialize.
<?xml version="1.0" encoding="utf-8"?>
<Root1>
<name>Name1</name>
<company>Comp1</company>
<url>site.com</url>
<element d2p1:type="Element1" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<url>site1.com</url>
<price>15000</price>
<manufacturer_warranty>true</manufacturer_warranty>
<country_of_origin>Япония</country_of_origin>
</element>
<element d2p1:type="Element2" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<url>site2.com</url>
<price>100</price>
<language>lg</language>
<binding>123</binding>
</element>
</Root1>
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string FILENAME = #"c:\temp\test.xml";
Root1 root1 = new Root1() {
Name = "Name1",
Company = "Comp1",
Url = "site.com",
ElementList = new List<Element>() {
new Element1() {
Url = "site1.com",
Price = "15000",
mw = "true",
co = "Япония"
},
new Element2() {
Url = "site2.com",
Price = "100",
lg = "lg",
bind = "123"
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Root1));
StreamWriter writer = new StreamWriter(FILENAME);
XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
_ns.Add("", "");
serializer.Serialize(writer, root1, _ns);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Root1));
XmlTextReader reader = new XmlTextReader(FILENAME);
Root1 newRoot1 = (Root1)xs.Deserialize(reader);
}
}
[XmlRoot("Root1")]
public class Root1
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("company")]
public string Company { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("element")]
public List<Element> ElementList { get; set; }
}
[XmlInclude(typeof(Element1))]
[XmlInclude(typeof(Element2))]
[XmlRoot("element")]
public class Element
{
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("price")]
public string Price { get; set; }
}
[XmlRoot("element1")]
public class Element1 : Element
{
[XmlElement("manufacturer_warranty")]
public string mw { get; set; }
[XmlElement("country_of_origin")]
public string co { get; set; }
}
[XmlRoot("element2")]
public class Element2 : Element
{
[XmlElement("language")]
public string lg { get; set; }
[XmlElement("binding")]
public string bind { get; set; }
}
}
Code below matches better with your posted XML. You need to compare the generated xml with your xml.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string FILENAME = #"c:\temp\test.xml";
Root1 root1 = new Root1()
{
Name = "Name1",
Company = "Comp1",
Url = "site.com",
cElement = new Elements() {
ElementList = new List<Element>() {
new Element1() {
Url = "site1.com",
Price = "15000",
mw = "true",
co = "Япония"
},
new Element2() {
Url = "site2.com",
Price = "100",
lg = "lg",
bind = "123"
}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Root1));
StreamWriter writer = new StreamWriter(FILENAME);
XmlSerializerNamespaces _ns = new XmlSerializerNamespaces();
_ns.Add("", "");
serializer.Serialize(writer, root1, _ns);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Root1));
XmlTextReader reader = new XmlTextReader(FILENAME);
Root1 newRoot1 = (Root1)xs.Deserialize(reader);
}
}
[XmlRoot("Root1")]
public class Root1
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("company")]
public string Company { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("elements")]
public Elements cElement { get; set; }
}
[XmlRoot("elements")]
public class Elements
{
[XmlElement("element")]
public List<Element> ElementList { get; set; }
}
[XmlInclude(typeof(Element1))]
[XmlInclude(typeof(Element2))]
[XmlRoot("element", Namespace = "")]
public class Element
{
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("price")]
public string Price { get; set; }
}
[XmlRoot("element1", Namespace = "")]
public class Element1 : Element
{
[XmlElement("manufacturer_warranty")]
public string mw { get; set; }
[XmlElement("country_of_origin")]
public string co { get; set; }
}
[XmlRoot("element2", Namespace = "")]
public class Element2 : Element
{
[XmlElement("language")]
public string lg { get; set; }
[XmlElement("binding")]
public string bind { get; set; }
}
}​

Xml deserialization with nested tags not working

I need to deserialize a XML file to a object. Following is the XML content:
<?xml version="1.0" encoding="utf-8" ?>
<PdfFile>
<PageTitle DocumentName="Sequence Diagram" Version="Version 4" >Title</PageTitle>
<LogoPath>C:\logo.png</LogoPath>
<Modules>
<Module Id="1" MainTitle="Module1">
<SubModules>
<SubModule>
<Title>SubModule1</Title>
<Path>SubModule1 Path</Path>
<Description>SubModule1 Desc</Description>
</SubModule>
<SubModule>
<Title>SubModule2</Title>
<Path>SubModule2 Path</Path>
<Description>SubModule2 Desc</Description>
</SubModule>
</SubModules>
</Module>
<Module Id="2" MainTitle="Module2">
<SubModules>
<SubModule>
<Title>SubModule1</Title>
<Path>SubModule1 Path</Path>
<Description>SubModule1 Desc</Description>
</SubModule>
</SubModules>
</Module>
</Modules>
</PdfFile>
Following is the class file I created, for the above xml file.
using System;
using System.Xml.Serialization;
namespace PDFCreation.Objects
{
[Serializable]
[XmlRoot("PdfFile")]
public class PdfFile2
{
[XmlElement("PageTitle")]
public PageTitle FirstPage { get; set; }
[XmlElement("LogoPath")]
public string LogoPath { get; set; }
[XmlArray("Modules")]
[XmlArrayItem("Module", typeof(Module))]
public Module[] Modules { get; set; }
}
[Serializable]
public class Module
{
[XmlAttributeAttribute("Id")]
public int Id { get; set; }
[XmlAttributeAttribute("MainTitle")]
public string MainTitle { get; set; }
[XmlArray("SubModules")]
[XmlArrayItem("SubModule", typeof(SubModule))]
public SubModule[] Modules { get; set; }
}
[Serializable]
public class SubModule
{
[XmlElement("Title")]
public string Title { get; set; }
[XmlElement("Path")]
public string Path { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
}
[Serializable]
public class PageTitle
{
[XmlText]
public string Title { get; set; }
[XmlAttribute]
public string DocumentName { get; set; }
[XmlAttribute]
public string Version { get; set; }
}
}
On deserializing, I'm not getting any error. But the modules inside PdfFile object always returns null. I tried to use the generated class from xsd.exe. But still the same thing is happening.
Please help me to find issue in the code/xml and why it is not deserializing fully?
Thanks!!!
Edited:
My C# code:
public class Program
{
private static readonly string XmlPath = ConfigurationManager.AppSettings["XmlPath"];
static void Main(string[] args)
{
try
{
ReadXml();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
}
private static void ReadXml()
{
if (!File.Exists(XmlPath))
{
Console.WriteLine("Error: Xml File Not exists in the path: {0}", XmlPath);
return;
}
using (var reader = new StreamReader(XmlPath))
{
var serializer = new XmlSerializer(typeof(PdfFile2));
var result = (PdfFile2)serializer.Deserialize(reader);
//other code here
}
}
}
Using nothing but you supplied code/xml and putting in the missing closing tags I got it to deserialize using this Main-class:
using System.IO;
using System.Xml.Serialization;
using PDFCreation.Objects;
public class Test
{
static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(PdfFile2));
PdfFile2 pdf = (PdfFile2)ser.Deserialize(File.OpenRead("test.xml"));
}
}
What does your deserialization code look like?

Categories