XML

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.Xml.Serialization;using System.IO;namespace XML_Ser{ [XmlRoot(ElementName = "Card", IsNullable = false, Namespace = "")] public class Card { [XmlElement("Card_ID", Order = 1)] public string ID { get; set; } [XmlElement("CardItems", typeof(CardItems),Order=2)] public CardItems Items { get; set; } } [Serializable] public class CardItems:List { } [Serializable] public class CardItem { [XmlAttribute] public string ID { get; set; } [XmlAttribute] public string Name { get; set; } [XmlElement("Height",Order=2)] public Int32 Height { get; set; } [XmlElement("Width", Order = 1)] public Int32 Width { get; set; } } public class XmlSer where T:class { public XmlSer() { } public XmlSer(string Path) { this.Path = Path; } public string Path { get; private set; } public T GetObj() { XmlSerializer xmls = new XmlSerializer(typeof(T)); using (FileStream fs = new FileStream(Path, FileMode.Open)) { return xmls.Deserialize(fs) as T; } } public void Save(T obj) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer xmls = new XmlSerializer(typeof(T)); XmlWriterSettings sets = new XmlWriterSettings(); sets.Encoding = Encoding.UTF8; sets.OmitXmlDeclaration = false; using (FileStream fs = new FileStream(Path, FileMode.Create)) { XmlWriter writer = XmlWriter.Create(fs, sets); xmls.Serialize(writer, obj,ns); writer.Close(); } } }}using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace XML_Ser{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Card card = new Card() { ID = "1" }; CardItem cardItem01 = new CardItem() { ID = "1", Name = "测试1", Height = 120, Width = 130 }; CardItem cardItem02 = new CardItem() { ID = "2", Name = "测试2", Height = 100, Width = 140 }; CardItems cardItems = new CardItems(); cardItems.Add(cardItem01); cardItems.Add(cardItem02); card.Items = cardItems; var xmls = new XmlSer("Test.xml"); xmls.Save(card); } private void button2_Click(object sender, EventArgs e) { var xmls = new XmlSer("Test.xml"); var card= xmls.GetObj(); var items = from n in card.Items where n.ID=="2" select n; foreach (CardItem item in items) { MessageBox.Show(string.Format("item.ID:{0},item.Name:{01},item.Height:{2},item.Width:{3}", item.ID, item.Name, item.Height, item.Width)); } } }}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值