好的,所以我有2个班级
public class PRData
{
public DateTime PRDate { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
一个是
public class MonthData
{
public string Months { get; set; }
public List<PRData> PrList { get; set; }
}
现在我创建了MonthData
和PRData
类的实例,并填写了一些数据。
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;
现在我正在尝试将此Object转换为xml
string xml = Helper.GetXMLFromObject(mon);
我收到的xml是
<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>
有没有办法删除PrList
标记,以便xml看起来像
<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>
我正在使用的函数是将对象转换为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);
}
}
注意: 的 我期待的解决方案是在我的类中进行一些更改而不是在将对象转换为上面给出的xml的函数中
答案 0 :(得分:2)
只需将XmlElement
属性应用于PrList
属性:
using System.Xml.Serialization;
...
[XmlElement]
public List<PRData> PrList { get; set; }