Xml序列化的Xml Root()不起作用

时间:2009-09-17 19:21:54

标签: c# xml-serialization xmlroot

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

的XML文件
<ScheduledShows>
    <ScheduledShowElement>...</ScheduledShowElement>
    <ScheduledShowElement>...</ScheduledShowElement>
    <ScheduledShowElement>...</ScheduledShowElement>
</ScheduledShows>

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

<ScheduledShows>
    <ScheduledShow>...<ScheduledShow>
    <ScheduledShow>...<ScheduledShow>
    <ScheduledShow>...<ScheduledShow
</ScheduledShows>

基本上,节点的名称未被覆盖。如何让我的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<ScheduledShow>)GetSheduledShowsByDateTime(selectedDateTime, size)));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        public static IList<ScheduledShow> GetSheduledShowsByDateTime(DateTime date, int size)
        {
            List<ScheduledShow> shows = new List<ScheduledShow>();
            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<ScheduledShow> shows)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<ScheduledShow>), 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;
        }

        /// <summary>
        /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        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文件

 <?xml version="1.0" encoding="utf-8"?>
<ScheduledShows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ScheduledShow>
        <AirTime xmlns="http://example.books.com">2009-09-17T10:20:00</AirTime>
        <StationId xmlns="http://example.books.com">770</StationId>
        <ScheduleRowId xmlns="http://example.books.com">17666100</ScheduleRowId>
        <StoryLine xmlns="http://example.books.com">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&amp;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&amp;rsquo;s critters vie for egg watching rights, so they can be first to be called Mama!  Or Poppa!</StoryLine>
        <Title xmlns="http://example.books.com">Disappearing Act / Great Eggspectations</Title>
        <ProgramId xmlns="http://example.books.com">2202</ProgramId>
        <Genre xmlns="http://example.books.com">Animated</Genre>
        <ProgramName xmlns="http://example.books.com">Willa's Wild Life</ProgramName>
        <SimsTitleId xmlns="http://example.books.com">68914</SimsTitleId>
        <ShowUrl xmlns="http://example.books.com">willas_wildlife</ShowUrl>
        <CssClass xmlns="http://example.books.com">none</CssClass>
    </ScheduledShow>
    <ScheduledShow>
        <AirTime xmlns="http://example.books.com">2009-09-17T10:45:00</AirTime>
        <StationId xmlns="http://example.books.com">770</StationId>
        <ScheduleRowId xmlns="http://example.books.com">17666105</ScheduleRowId>
        <StoryLine xmlns="http://example.books.com">It&amp;rsquo;s Club Day in Gloomsville. The gang splinter off to form clubs and prepare for the club&amp;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&amp;rsquo;t met them yet &amp;ndash; they&amp;rsquo;re imaginary. </StoryLine>
        <Title xmlns="http://example.books.com">Skull Boys Don't Cry</Title>
        <ProgramId xmlns="http://example.books.com">1418</ProgramId>
        <Genre xmlns="http://example.books.com">Animated</Genre>
        <ProgramName xmlns="http://example.books.com">Ruby Gloom</ProgramName>
        <SimsTitleId xmlns="http://example.books.com">54297</SimsTitleId>
        <ShowUrl xmlns="http://example.books.com">rubygloom</ShowUrl>
        <CssClass xmlns="http://example.books.com">none</CssClass>
    </ScheduledShow>
    <ScheduledShow>
        <AirTime xmlns="http://example.books.com">2009-09-17T11:10:00</AirTime>
        <StationId xmlns="http://example.books.com">770</StationId>
        <ScheduleRowId xmlns="http://example.books.com">17666113</ScheduleRowId>
        <StoryLine xmlns="http://example.books.com">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.</StoryLine>
        <Title xmlns="http://example.books.com">Erky's Birthday / Location Location Location</Title>
        <ProgramId xmlns="http://example.books.com">1347</ProgramId>
        <Genre xmlns="http://example.books.com">Animated</Genre>
        <ProgramName xmlns="http://example.books.com">Erky Perky</ProgramName>
        <SimsTitleId xmlns="http://example.books.com">49009</SimsTitleId>
        <ShowUrl xmlns="http://example.books.com">erky_perky</ShowUrl>
        <CssClass xmlns="http://example.books.com">none</CssClass>
    </ScheduledShow>
    <ScheduledShow>
        <AirTime xmlns="http://example.books.com">2009-09-17T11:35:00</AirTime>
        <StationId xmlns="http://example.books.com">770</StationId>
        <ScheduleRowId xmlns="http://example.books.com">17666116</ScheduleRowId>
        <StoryLine xmlns="http://example.books.com">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</StoryLine>
        <Title xmlns="http://example.books.com">ZOOPERCAR CAPER</Title>
        <ProgramId xmlns="http://example.books.com">311</ProgramId>
        <Genre xmlns="http://example.books.com" />
        <ProgramName xmlns="http://example.books.com">George Shrinks</ProgramName>
        <SimsTitleId xmlns="http://example.books.com">25371</SimsTitleId>
        <ShowUrl xmlns="http://example.books.com" />
        <CssClass xmlns="http://example.books.com">none</CssClass>
    </ScheduledShow>
    <ScheduledShow>
        <AirTime xmlns="http://example.books.com">2009-09-17T11:35:00</AirTime>
        <StationId xmlns="http://example.books.com">770</StationId>
        <ScheduleRowId xmlns="http://example.books.com">17666116</ScheduleRowId>
        <StoryLine xmlns="http://example.books.com">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</StoryLine>
        <Title xmlns="http://example.books.com">ZOOPERCAR CAPER</Title>
        <ProgramId xmlns="http://example.books.com">311</ProgramId>
        <Genre xmlns="http://example.books.com" />
        <ProgramName xmlns="http://example.books.com">George Shrinks</ProgramName>
        <SimsTitleId xmlns="http://example.books.com">25371</SimsTitleId>
        <ShowUrl xmlns="http://example.books.com">george_shrinks</ShowUrl>
        <CssClass xmlns="http://example.books.com">none</CssClass>
    </ScheduledShow>
</ScheduledShows>

4 个答案:

答案 0 :(得分:15)

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

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
    {

      ...
    }
}

答案 1 :(得分:10)

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

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我还使用了 XmlType 属性 [XmlType("")] 并且有效。

[XmlRoot][XmlType] 仅适用于类。

[XmlElement] 仅用于属性。

看到这个:https://docs.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes#controlling-serialization-of-classes-using-xmlrootattribute-and-xmltypeattribute

相关问题