用于Xml Serilization的XmlRoot()不起作用

我正在尝试让我的httphandler打印出格式为的XML文件:

 ... ... ...  

但由于某种原因,ScheduledShow.cs中的属性XmlRoot(“ScheduledShowElement”)不能按我希望的方式工作。 相反,我得到的输出是:

  ... ... ...<ScheduledShow  

基本上,节点的名称没有被覆盖。 如何让我的xml序列化程序将节点标记为?

下面是我的代码和xml输出。 谢谢!

OneDayScheduleHandler.cs

 using System; using System.Collections.Generic; using System.Web; using System.Xml.Serialization; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data.Common; using System.Data; using System.IO; using System.Xml; using System.Text; using CommunityServer.Scheduler; namespace CommunityServer.Scheduler { public class OneDayScheduleHandler : IHttpHandler { private readonly int NoLimitOnSize = -1; public void ProcessRequest(HttpContext context) { int offsetInDays, timezone, size; DateTime selectedDateTime; Int32.TryParse(context.Request.QueryString["timezone"], out timezone); Int32.TryParse(context.Request.QueryString["daysToOffset"], out offsetInDays); if (!String.IsNullOrEmpty(context.Request.QueryString["size"])) { Int32.TryParse(context.Request.QueryString["size"], out size); } else { size = NoLimitOnSize; } if (timezone < (int)ScheduleConstants.TimeZone.Eastern) { selectedDateTime = DateTime.Now.AddMinutes(-180); } else { selectedDateTime = DateTime.Now; } selectedDateTime = selectedDateTime.AddDays(offsetInDays); context.Response.ContentType = "text/xml"; context.Response.Write(SerializeToXML((List)GetSheduledShowsByDateTime(selectedDateTime, size))); } public bool IsReusable { get { return false; } } public static IList GetSheduledShowsByDateTime(DateTime date, int size) { List shows = new List(); Database db = DatabaseFactory.CreateDatabase("TVScheduleSqlServer"); DbCommand cmd = db.GetStoredProcCommand("sp_get_YTVDayShowlist"); db.AddInParameter(cmd, "@CurrentDay", DbType.DateTime, date); IDataReader reader = db.ExecuteReader(cmd); int i = 0; while (reader.Read() && (i < size || size == -1)) { ScheduledShow show = new ScheduledShow(); show.AirTime = Convert.ToDateTime(reader["Airing_datetime"].ToString()); show.StationId = Convert.ToInt32(reader["Station_id"].ToString()); show.ScheduleRowId = Convert.ToInt32(reader["id"].ToString()); show.StoryLine = reader["StoryLine"].ToString(); show.Title = reader["Title_name"].ToString(); show.SimsTitleId = Convert.ToInt32(reader["Sims_title_id"].ToString()); show.ProgramId = Convert.ToInt32(reader["Program_id"].ToString()); show.Genre = reader["Genre_list"].ToString(); show.ProgramName = reader["program_name"].ToString(); show.ShowUrl = reader["ShowURL"].ToString(); show.CssClass = reader["CSSCLASS"].ToString(); shows.Add(show); i++; } reader.Close(); reader.Dispose(); return shows; } static public string SerializeToXML(List shows) { XmlSerializer serializer = new XmlSerializer(typeof(List), new XmlRootAttribute("ScheduledShows")); //StringWriter stringWriter = new StringWriter(); string xml; using (MemoryStream memoryStream = new MemoryStream()) { using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8)) { serializer.Serialize(xmlTextWriter, shows); using (MemoryStream memoryStream2 = (MemoryStream)xmlTextWriter.BaseStream) { xml = UTF8ByteArrayToString(memoryStream2.ToArray()); } } } return xml; } ///  /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String. ///  /// Unicode Byte Array to be converted to String /// String converted from Unicode Byte Array private static String UTF8ByteArrayToString(Byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); String constructedString = encoding.GetString(characters); return (constructedString); } } } 

ScheduledShow.cs

 using System; using System.Xml.Serialization; namespace CommunityServer.Scheduler { [XmlRoot("ScheduledShowElement")] public class ScheduledShow { [XmlElement("AirTime")] public DateTime AirTime { get; set; } [XmlElement("StationId")] public int StationId { get; set; } [XmlElement("ScheduleRowId")] public int ScheduleRowId { get; set; } [XmlElement("StoryLine")] public string StoryLine { get; set; } [XmlElement("Title")] public string Title { get; set; } [XmlElement("ProgramId")] public int ProgramId { get; set; } [XmlElement("Genre")] public string Genre { get; set; } [XmlElement("ProgramName")] public string ProgramName { get; set; } [XmlElement("SimsTitleId")] public int SimsTitleId { get; set; } [XmlElement("ShowUrl")] public string ShowUrl { get; set; } [XmlElement("CssClass")] public string CssClass { get; set; } } } 

输出xml文件

     2009-09-17T10:20:00 770 17666100 When Dooley demonstrates his newest hobby, magic, Willa gets an idea. A huge backyard magic show! Starring the Great Doolini and his amazing disappearing elephant trick! Unfortunately, Lou the elephant misunderstands and thinks Willa wants him to disappear for real. In the middle of the show Willa must find Lou and apologize so he&rsquo;ll reappear! / When the animals and Willa discover an egg in their backyard, their parental propriety kicks in. Especially when Dooley relates a factoid about young hatchlings imprinting on the first critter they see. Willa&rsquo;s critters vie for egg watching rights, so they can be first to be called Mama! Or Poppa! Disappearing Act / Great Eggspectations 2202 Animated Willa's Wild Life 68914 willas_wildlife none   2009-09-17T10:45:00 770 17666105 It&rsquo;s Club Day in Gloomsville. The gang splinter off to form clubs and prepare for the club&rsquo;s appearance in the big Gloomsville parade. Skull Boy forms the coolest club of all with some new jazzy skeletal friends that no one ever sees. At first no one believes Skull Boy has these new friends since every time they want to meet them, they disappear. When pressed for details, she admits she hasn&rsquo;t met them yet &ndash; they&rsquo;re imaginary.  Skull Boys Don't Cry 1418 Animated Ruby Gloom 54297 rubygloom none   2009-09-17T11:10:00 770 17666113 When Mad Margaret gets trapped in a jar she becomes a source of entertainment for Erky./Erky and Perky need a place to live and who better to find it for them than Frenzel. Erky's Birthday / Location Location Location 1347 Animated Erky Perky 49009 erky_perky none   2009-09-17T11:35:00 770 17666116 SYNOPSIS:The Joyco toy company has heard about George and his Zoopercar and they want to market it as their newest toy. But George isn't interested in selling his prized mode of transportation. Afterall, he and his Dad built it together and no one can take that special bond away from him. But two Joyco toy employees, Barry and Steve, have other plans. If George won't sell it to them, they will just have to take it, which they do. But once their boss, Big Ed Easy finds out that George has be ZOOPERCAR CAPER 311  George Shrinks 25371  none   2009-09-17T11:35:00 770 17666116 SYNOPSIS:The Joyco toy company has heard about George and his Zoopercar and they want to market it as their newest toy. But George isn't interested in selling his prized mode of transportation. Afterall, he and his Dad built it together and no one can take that special bond away from him. But two Joyco toy employees, Barry and Steve, have other plans. If George won't sell it to them, they will just have to take it, which they do. But once their boss, Big Ed Easy finds out that George has be ZOOPERCAR CAPER 311  George Shrinks 25371 george_shrinks none   

我在这里找到了一个问题的答案:

http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/4b228734-a209-445a-991c-0420b381ac93

我只是使用了[XmlType("")]而且有效。

 using System; using System.Xml.Serialization; namespace CommunityServer.Scheduler { [XmlType("ScheduledShowElement")] public class ScheduledShow { ... } } 

[XmlRoot(...)]仅影响最外层元素( ... )。 我怀疑你想要[XmlElement(...)] 。 当然,另一种方法是编写一个对象包装器:

 [XmlRoot("SheduledShows")] public class Shows { [XmlElement("SheduledShowElement")] public List Shows {get;set;} } 

并序列化此包装器对象而不仅仅是列表。

您需要使用接收XmlAttributeOverrides的重载构造函数,并确保覆盖ScheduledShow类的名称。