In my project, legacy code generates xml which has following structure :
<Output>
<Template recordID=12>
<Employer type="String">
<Value>Google</Value>
<Value>GigaSoft inc.</Value>
</Employer>
<Designation type="String">
<Value>Google</Value>
</Designation>
<Duration type="String" />
</Template>
</Output>
I want to deserialize this xml into object which has following properties (I am using C#):
public class EmployerInfo
{
string[] _employerName;
string[] _designation;
string _duration;
}
I tried to deserialize above xml using following attributes around members (NOTE : I have simplified code. I know we should not make data members public. This code is just for experimental purpose)
[XmlElement("Template")]
public class EmployerInfo
{
[XmlElement("Employer")]
public string[] _employerName;
[XmlElement("Designation")]
public string[] _designation;
[XmlElement("Duration")]
public string _duration;
}
To deserialize, in main class I wrote :
XmlSerializer serial = new XmlSerializer(typeof(Output));
TextReader reader = new StreamReader(@"C:\sample_xml.xml");
EmployerInfo fooBar = (EmployerInfo)serial.Deserialize(reader);
reader.Close();
After executing above code, all the members in fooBar object are set to null (default values). I think this is because xml structure does not match with class structure.
I tried to automatically generate class using xsd command but it created seperate classes for each of the data member .
I tried to g开发者_运维百科ive element names like XmlElement("Employer.Value") , XmlElement("Template.Employer.Value") but this also didnt work.
Can anyone please suggest some way to fit this xml into a EmployerInfo
class ?
Thanks in advance
Try:
using System.IO;
using System.Xml.Serialization;
[XmlType("Template")]
public class EmployerInfo
{
[XmlArray("Employer"), XmlArrayItem("Value")]
public string[] _employerName;
[XmlArray("Designation"), XmlArrayItem("Value")]
public string[] _designation;
[XmlElement("Duration")]
public string _duration;
}
public class Output
{
public EmployerInfo Template { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializer serial = new XmlSerializer(typeof(Output));
using (var reader = new StringReader(@"<Output>
<Template recordID=""12"">
<Employer type=""String"">
<Value>Google</Value>
<Value>GigaSoft inc.</Value>
</Employer>
<Designation type=""String"">
<Value>Google</Value>
</Designation>
<Duration type=""String"" />
</Template>
</Output>"))
{
EmployerInfo fooBar = ((Output)serial.Deserialize(reader)).Template;
}
}
}
Note also tat the type returned from XmlSerializer(typeof(Output))
's deserialize method is going to be a Output
record.
精彩评论