【笔记】【LINQ编程技术内幕】第二十章 从非XML数据构造XML

从CSV文件构造XML

CSV文件是一种文本文件,包含的是用逗号分隔的值;一般来说,一行文本就表示一条独立记录。可以根据逗号来拆分出各个值,然后使用函数构造将整个文本文件转换成XML。

class Program
{
	static void Main(string[] args)
	{
		string all = GetQuotes("MSFT GOOG DELL");
		string[] quotes = all.Replace("<b>", "").Replace("</b>", "").Replace("\"", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);


		// Read into an array of strings.
		XElement stockQuotes = new XElement("Root",
			  from quote in quotes
			  let fields = quote.Split(new char[] { ',', '-' },StringSplitOptions.RemoveEmptyEntries)
			  select
				  new XElement("Company", fields[0].Trim(),
				  new XElement("LastPrice", fields[2].Trim(),
					new XAttribute("Time", fields[1].Trim())),
					new XElement("HighToday", fields[3].Trim())));

		stockQuotes.Save("..\\..\\quotes.xml");
		Console.WriteLine(stockQuotes);
	}

	static string GetQuotes(string stocks)
	{
		string url = @"http://quote.yahoo.com/d/quotes.csv?s={0}&f=nlh";

		HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create(string.Format(url, stocks));
		HttpWebResponse response = (HttpWebResponse)request.GetResponse();

		using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
		{
			try
			{
				return reader.ReadToEnd();
			}
			finally
			{
				// don't need to close the reader because Dispose does
				response.Close();
			}
		}
	}
}

从XML生成文本文件

<?xml version="1.0" encoding="utf-8"?>
<Blackjack>
  <Player Name="Player 1">
    <Statistics>
      <AverageAmountLost>-28.125</AverageAmountLost>
      <AverageAmountWon>30.681818181818183</AverageAmountWon>
      <Blackjacks>1</Blackjacks>
      <Losses>8</Losses>44
      <NetAverageWinLoss>5.9210526315789478</NetAverageWinLoss>
      <NetWinLoss>112.5</NetWinLoss>
      <PercentageOfBlackJacks>0.041666666666666664</PercentageOfBlackJacks>
      <PercentageOfLosses>33.333333333333329</PercentageOfLosses>
      <PercentageOfPushes>16.666666666666664</PercentageOfPushes>
      <PercentageOfWins>45.833333333333329</PercentageOfWins>
      <Pushes>4</Pushes>
      <Surrenders>1</Surrenders>
      <TotalAmountLost>-225</TotalAmountLost>
      <TotalAmountWon>337.5</TotalAmountWon>
      <Wins>11</Wins>
    </Statistics>
  </Player>
</Blackjack>
class Program
{
	static void Main(string[] args)
	{
		XElement blackjackStats = XElement.Load("..\\..\\CurrentStats.xml");
		string file =
		  (from elem in blackjackStats.Elements("Player")
		   let statistics = elem.Element("Statistics")
		   select string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}" +
		 "{9},{10},{11},{12},{13},{14},{15}{16}",
		   (string)elem.Attribute("Name"),
		   (string)statistics.Element("AverageAmountLost"),
		   (string)statistics.Element("AverageAmountWon"),
		   (string)statistics.Element("Blackjacks"),
		   (string)statistics.Element("Losses"),
		   (string)statistics.Element("NetAverageWinLoss"),
		   (string)statistics.Element("NetWinLoss"),
		   (string)statistics.Element("PercentageOfBlackJacks"),
		   (string)statistics.Element("PercentageOfLosses"),
		   (string)statistics.Element("PercentageOfPushes"),
		   (string)statistics.Element("PercentageOfWins"),
		   (string)statistics.Element("Pushes"),
		   (string)statistics.Element("Surrenders"),
		   (string)statistics.Element("TotalAmountLost"),
		   (string)statistics.Element("TotalAmountWon"),
		   (string)statistics.Element("Wins"),
		   Environment.NewLine)).
			  Aggregate(new StringBuilder(),
				(builder, str) => builder.Append(str),
				  builder => builder.ToString());

		Console.WriteLine(file);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhy29563

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值