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:
What does your deserialization code look like?