我有以下代码来解析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; }
}
}
}
}
}
}
}
答案 0 :(得分:0)
Xml命名空间;尝试
[XmlElement("Project", Namespace="http://schemas.microsoft.com/project")]