代码如何构建出来下面格式的xml文件
<images>
<image src="xml/images/01.jpg"/>
<image src="xml/images/02.jpg"/>
<image src="xml/images/03.jpg"/>
</images>
体验一下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")) ));
[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; } }
然后你就可以初始化images实体,调用方法生成XML了
推荐二楼的方法,不用自己去解析xml中相应的属性等内容,也比较灵活,xml中的属性名变了,在类中相应的属性上改一下AttributeName的值就可以了
值得推荐2楼的做法