1
我有以下代碼在C#中對xml字符串進行deseriaze。C#反序列化嵌套的xml
一切工作正常,我可以將其反序列化爲一個對象。但是,ProjectNode值始終爲空。
有人可以幫我做這個代碼工作或指出我錯過了什麼?
樣本XML已包含在下面的代碼中。
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DeserializeSample
{
class Program
{
static string XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><response clientos=\"Windows\" datetimepattern=\"M/d/yyyy h:mm:ss a\"><info><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?><transaction loglevel=\"0\" type=\"response\"><arguments><argument name=\"id\">1</argument><argument name=\"foredit\">True</argument><argument name=\"ScheduleOn\">Estimated</argument><argument name=\"xml\"><Project xmlns=\"http://schemas.microsoft.com/project\"><UID>0</UID><ID>0</ID></Project></argument></arguments></transaction>]]></info></response>";
static void Main(string[] args)
{
ProjectResponse projectResponse = CreateFromXml(XML, typeof(ProjectResponse)) as ProjectResponse;
}
public static object CreateFromXml(string data, Type msfRequestResponseType)
{
object projectResponse = null;
try
{
XmlSerializer deserializer = new XmlSerializer(msfRequestResponseType, "");
XmlReaderSettings settings = new XmlReaderSettings() { ProhibitDtd = true };
// We have content in the part so create xml reader and load the xml into XElement.
using (XmlReader reader = XmlReader.Create(new StringReader(data), settings))
{
projectResponse = deserializer.Deserialize(reader);
}
}
catch (Exception Ex)
{
throw;
}
return projectResponse;
}
}
[XmlRoot("response")]
[Serializable]
public class ProjectResponse
{
[XmlAnyAttribute()]
public XmlAttribute[] ResponseAttributes { get; set; }
[XmlElement("info")]
public ProjectResponseInfoTag InfoTag { get; set; }
public class ProjectResponseInfoTag
{
private string infoText = string.Empty;
[XmlText]
public string InfoText
{
get { return infoText; }
set
{
infoText = value;
Transaction = Program.CreateFromXml(infoText, typeof(ProjectTransaction)) as ProjectTransaction;
}
}
[XmlElement("transaction")]
public ProjectTransaction Transaction { get; set; }
[XmlRoot("transaction")]
public class ProjectTransaction
{
[XmlAnyAttribute]
public XmlAttribute[] TransactionAttributes { get; set; }
[XmlElement("arguments")]
public ProjectArguments Arguments { get; set; }
public class ProjectArguments
{
[XmlElement("argument")]
public List<ProjectArgument> ArgList { get; set; }
public class ProjectArgument
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlText]
public string ArgValue { get; set; }
[XmlElement("Project")]
public Project ProjectNode { get; set; }
public class Project
{
[XmlAnyElement()]
public XmlElement[] ProjectElements { get; set; }
[XmlAnyAttribute()]
public XmlAttribute[] ProjectAttributes { get; set; }
}
}
}
}
}
}
}
它完美地工作。謝謝! – user2632730