のえら

技術備忘とかメモとか.間違いはつっこんでいただきたい所存.アフィリエイトはやっていません.

C#でXMLを読み込んでほげほげする

PCのデータを整理してたら入社後半年くらいでやった研修のネタがでてきたのでめもめも。
C#XMLのファイルを読み込んでオブジェクトを生成するとかなんとか。
2010年の話だから古くて使えんかもしれん。
一部省略。


読み込むXML

<?xml version="1.0" encoding="utf-8" ?>
<Goods>
  <Content TradeName="リンゴ" Sum="120" ImagePath="apple.gif" Count="10"/>
  <Content TradeName="メロンソーダ" Sum="150" ImagePath="melon.gif" Count="5"/>
  <Content TradeName="オレンジ" Sum="130" ImagePath="orange.gif" Count="8"/>
  <Content TradeName="スイカ" Sum="220" ImagePath="" Count="1"/>
  <Content TradeName="パイナップル" Sum="160" ImagePath="" Count="3"/>
</Goods>

読み込んでGoosStockオブジェクトを作成する

using (XmlReader xmlReader = XmlReader.Create(filePath))
{
	// 読み込んだデータをリストにする
	_stock = (from element in XDocument.Load(xmlReader).Element("Goods").Elements("Content")
	select new GoodsStock
	{
		Goods = Goods.CreateGoods(
		(string)element.Attribute("TradeName"),
		(string)element.Attribute("ImagePath"),
		(int?)element.Attribute("Sum")),
		Count = (int)element.Attribute("Count")
	}).ToDictionary(goodsstock => goodsstock.Goods.TradeName);
}
foreach (var stock in _stock)
{
	stock.Value.Selled += new EventHandler(Value_Selled);
	stock.Value.SellOuted += new EventHandler(Value_SellOuted);
}