4
我需要將XML文件反序列化爲對象。以下是XML內容:嵌套標記無法正常工作的Xml反序列化
<?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>
以下是我爲上述xml文件創建的類文件。
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; }
}
}
關於反序列化,我沒有得到任何錯誤。但是PdfFile對象中的模塊總是返回null。我試圖從xsd.exe使用生成的類。但仍然發生同樣的事情。
請幫我找到代碼/ XML中的問題,以及它爲什麼不完全反序列化?
謝謝!
編輯:
我的C#代碼:
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
}
}
}
這是完整的XML嗎?它似乎缺少結尾標籤(如上所述)的結尾標籤'' – Tung 2012-04-03 11:03:37
,看起來都很好。你能展示你的反序列化代碼嗎? – paul 2012-04-03 11:15:47
對不起!正確格式化xml並添加反序列化代碼。感謝您指出它。 – 2012-04-03 11:37:19