首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

复杂格式的XML序列化,该怎么解决

2013-08-04 
复杂格式的XML序列化?xml version1.0?HotelGeosHotelGeoListHotelGeo Country中国 ProvinceN

复杂格式的XML序列化
<?xml version="1.0"?>
<HotelGeos>
  <HotelGeoList>
    <HotelGeo Country="中国" ProvinceName="河北" ProvinceId="0500" CityName="南戴河" CityCode="0504">
      <Districts>
        <Location Id="0001" Name="海滨浴场"/>
      </Districts>
      <CommericalLocations>
        <Location Id="050402" Name="海滨地区"/>
      </CommericalLocations>
      <LandmarkLocations>
        <Location Id="0001" Name="南戴河"/>
      </LandmarkLocations>
    </HotelGeo>
    <HotelGeo Country="中国" ProvinceName="河北" ProvinceId="0500" CityName="邢台" CityCode="0505">
      <Districts>
        <Location Id="0001" Name="市中心"/>
      </Districts>
      <CommericalLocations>
        <Location Id="050501" Name="市中心"/>     
      </CommericalLocations>
      <LandmarkLocations>
        <Location Id="0001" Name="人民公园"/>
      </LandmarkLocations>
    </HotelGeo>
  </HotelGeoList>
</HotelGeos>
像这种复杂格式的XML 怎么序列化成  多个 List<t>
[解决办法]
简单写了个,测试通过:


private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            HotelGeos result = Deserialize < HotelGeos>(File.ReadAllText("XMLFile1.xml"));
        }



        public static T Deserialize<T>(string xml)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            MemoryStream memoryStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(xml));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            object result = xs.Deserialize(memoryStream);
            return (T)result;
        }



实体类

     public class HotelGeos
     {
         [XmlArray]
         public List<HotelGeo> HotelGeoList { get; set; }
     }

    public class HotelGeo
    {
        [XmlAttribute]
        public string Country { get; set; }

        [XmlAttribute]
        public string ProvinceName { get; set; }

        [XmlAttribute]
        public string ProvinceId { get; set; }

        [XmlAttribute]
        public string CityName { get; set; }

        [XmlAttribute]
        public string CityCode { get; set; }

        [XmlArray]
        public List<Location> Districts { get; set; }

        [XmlArray]
        public List<Location> CommericalLocations { get; set; }

        [XmlArray]
        public List<Location> LandmarkLocations { get; set; }


    }

    public class Location
    {
        [XmlAttribute]
        public string Id { get; set; }

        [XmlAttribute]
        public string Name { get; set; }
    }

热点排行