您的位置:首页 > 其它

初识.net界面程序(9)--LINQ To XML

2017-05-15 12:42 357 查看
编写一个记录学生C#课成绩的XML文档,结构如下

<CScore>
<StuID>
<name>张三</name>
<score>86</score>
</StuID>
<StuID>
<name>李四</name>
<score>87</score>
</StuID>
<StuID>
<name>王五</name>
<score>87</score>
</StuID>
<StuID>
<name>刘七</name>
<score>88</score>
</StuID>
<StuID>
<name>张八</name>
<score>87</score>
</StuID>
</CScore>


给出一个分数,查找出所有成绩为次分数的学生姓名

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace 补充习题
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
textBox1.Anchor =
AnchorStyles.Left | AnchorStyles.Right
| AnchorStyles.Top | AnchorStyles.Bottom;
textBox1.ScrollBars = ScrollBars.Both;
foreach (var v in this.Controls)
{
Button btn = v as Button;
if (btn != null)
{
btn.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
btn.Click += btn_Click;
}
}
}

void btn_Click(object sender, EventArgs e)
{
string vlaue = textBox2.Text;
string s = (sender as Button).Text;
switch (s)
{
case "创建":
{

XElement xTree = new XElement("CScore",

new XElement("StuID",
new XElement("name", "张三"),
new XElement("score", 86)
),
new XElement("StuID",
new XElement("name", "李四"),
new XElement("score", 87)
),
new XElement("StuID",
new XElement("name", "王五"),
new XElement("score", 87)
),
new XElement("StuID",
new XElement("name", "刘七"),
new XElement("score", 88)
),
new XElement("StuID",
new XElement("name", "张八"),
new XElement("score", 87)
)
);

textBox1.Text = xTree.ToString();
xTree.Save("test.xml");
break;
}
case "查询":
{
StringBuilder sb = new StringBuilder();
XElement CScore = null;
try
{
CScore = XElement.Load("test.xml");
}
catch
{
MessageBox.Show("请先执行【创建】");
return;
}
var q1 = from t in CScore.Elements("StuID")
select t;

var q2 = from t in q1
where (string)t.Element("score") == vlaue
select t.Element("name");
foreach (var v in q2)
{
sb.AppendLine(v.Value.ToString());
}
//sb.AppendLine();
textBox1.Text = sb.ToString();
break;
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml .net 界面 文档 结构