Reputation: 23801
OK so i have 2 classes
public class PRData
{
public DateTime PRDate { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
And one is
public class MonthData
{
public string Months { get; set; }
public List<PRData> PrList { get; set; }
}
Now i created an instance of the MonthData
and PRData
classes and filled in some data.
PRData pr = new PRData();
pr.Title = "hello";
pr.PRDate = DateTime.Now;
pr.Description = "Hello world";
List<PRData> prList =new List<PRData>();
prList.Add(pr);
prList.Add(pr);
MonthData mon = new MonthData();
mon.Months = "feb";
mon.PrList = prList;
Now i'm trying to convert this Object into an xml
string xml = Helper.GetXMLFromObject(mon);
The xml that i'm receiving is
<MonthData>
<Months>feb</Months>
<PrList>
<PRData>
<PRDate>2012-02-01T00:00:00</PRDate>
<Title>hello</Title>
<Description>Hello world</Description>
</PRData>
<PRData>
<PRDate>2012-02-01T00:00:00</PRDate>
<Title>hello</Title>
<Description>Hello world</Description>
</PRData>
</PrList>
</MonthData>
Is there any way to remove the PrList
tag so that the xml looks like
<MonthData>
<Months>feb</Months>
<PRData>
<PRDate>2012-02-01T00:00:00</PRDate>
<Title>hello</Title>
<Description>Hello world</Description>
</PRData>
<PRData>
<PRDate>2012-02-01T00:00:00</PRDate>
<Title>hello</Title>
<Description>Hello world</Description>
</PRData>
</MonthData>
The function that i'm using is below to convert object to xml
public static string GetXMLFromObject(object o)
{
try
{
XmlSerializer XmlS = new XmlSerializer(o.GetType());
StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);
XmlS.Serialize(tw, o);
return sw.ToString();
}
catch (Exception ex)
{
throw new DataAccessException("Could Not Serialize object : GetXMLFromObject" + " : " + ex.Message);
}
}
Note:: The solution that i'm looking forward to is by making some changes in my classes and not in the function to convert object to xml that i have given above
Upvotes: 0
Views: 67
Reputation: 292465
Just apply the XmlElement
attribute to the PrList
property:
using System.Xml.Serialization;
...
[XmlElement]
public List<PRData> PrList { get; set; }
Upvotes: 2