首页 > 代码库 > model转xml

model转xml

   private static string DataToXml_String(string strReturn)
        {
            Hotel r = new Hotel();
            r.HotelAttributes = new List<HotelAttribute>();
            for (int i = 0; i < 3; i++)
            {
                HotelAttribute ha = new HotelAttribute();
                ha.id = i.ToString();
                ha.name = "name" + i.ToString();
                ha.tel = "tel" + i.ToString();
                ha.city = "city" + i.ToString();
                ha.address = "address" + i.ToString();
                ha.strValue = " ";

                r.HotelAttributes.Add(ha);
            }

            strReturn = XmlSerializerHelp.Serializer(typeof(Hotel), r).Replace("> <", "><");
            return strReturn;
        }
//格式
<?xml version="1.0" encoding="utf-8"?>
<list>
     <hotel id="0" tel="tel0" address="address0" name="name0" city="city0"></hotel>
     <hotel id="1" tel="tel1" address="address1" name="name1" city="city1"></hotel>
     <hotel id="2" tel="tel2" address="address2" name="name2" city="city2"></hotel>
</list>
//model
 [Serializable]
    [XmlRoot("list")]
    public class Hotel
    {
        [XmlElement("hotel")]
        public List<HotelAttribute> HotelAttributes;
    }

   [Serializable]
    public class HotelAttribute
    {
        // 节点属性 
        [XmlAttribute]
        public string id { get; set; }
        [XmlAttribute]
        public string tel { get; set; }
        [XmlAttribute]
        public string address { get; set; }
        [XmlAttribute]
        public string name { get; set; }
        [XmlAttribute]
        public string city { get; set; }
        //不常用 节点值
        [XmlText]
        public string strValue { get; set; }
    }

 

model转xml