首页新闻找找看学习计划

asp.net如何构建自定义格式的xml

0
悬赏园豆:20 [待解决问题]

代码如何构建出来下面格式的xml文件

<images>
<image src="xml/images/01.jpg"/>
<image src="xml/images/02.jpg"/>
<image src="xml/images/03.jpg"/>
</images>

Ashe的主页 Ashe | 初学一级 | 园豆:67
提问于:2015-05-25 09:40
< >
分享
所有回答(4)
1

体验一下LINQ to XML的威力:

Console.WriteLine(new XElement("images",
    new XElement("image", new XAttribute("src", "xml/images/01.jpg")),
    new XElement("image", new XAttribute("src", "xml/images/02.jpg")),
    new XElement("image", new XAttribute("src", "xml/images/02.jpg"))
    ));
dudu | 园豆:41262 (高人七级) | 2015-05-25 09:55
1

[XmlRoot("image")]
public class image
{
[XmlAttribute("src")]
public string src{get;set;}

}
[XmlRoot("images")]
public class images
{

[XmlElement("image")]
public image[] image { get; set; }

}

/// <summary>
        /// 把XML转换成相应实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="XMLString"></param>
        /// <returns></returns>
        public static T XMLDeserialize<T>(string XMLString) where T : new()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                TextReader textReader = new StringReader(XMLString);
                XmlReader reader = XmlReader.Create(textReader);
                T model = (T)serializer.Deserialize(reader);
                return model;
            }
            catch (Exception ex)
            {
                Logging.Instance.FatalException("ConvertXML错误", ex);
            }
            return default(T);
        }
        /// <summary>
        /// 把实体转换成XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="XMLString"></param>
        /// <returns></returns>
        public static string XMLSerialize<T>(T model) where T : new()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding(false);
                    XmlTextWriter xtw = new XmlTextWriter(stream, utf8EncodingWithNoByteOrderMark);
                    serializer.Serialize(xtw, model, ns);
                    string xml = Encoding.UTF8.GetString(stream.ToArray());
                    return xml;
                }
            }
            catch (Exception ex)
            {
                Logging.Instance.ErrorException("XMLSerialize", ex);
                return string.Empty;
            }
        }
View Code

然后你就可以初始化images实体,调用方法生成XML了

 

Giant Liu | 园豆:888 (小虾三级) | 2015-05-25 15:07
0

推荐二楼的方法,不用自己去解析xml中相应的属性等内容,也比较灵活,xml中的属性名变了,在类中相应的属性上改一下AttributeName的值就可以了

junjieok | 园豆:779 (小虾三级) | 2015-05-26 17:36
0

值得推荐2楼的做法

| 园豆:750 (小虾三级) | 2015-05-26 22:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册