错误1当前上下文中不存在名称“File”
<%--程序名称:7-01.aspx--%>
<%--程序功能:XML树的创建和查询--%>
<%@ page language="C#" autoeventwireup="true"
codeFile="7-01.aspx.cs" inherits="_7_01"%>
<form id="form1" runat="server">
<asp:button id="btncreatXML" runat="server" text="创建XML树"
onclick="btncreatXML_click"/>
<asp:button id="btncqueryall" runat="server" text="查询全部"
onclick="btnqueryall_click"/>
<asp:button id="btnquery" runat="server" text="条件查询"
onclick="btnquery_click"/>
///<summary>
///创建XML树
///</summary>
private void CreateXML()
{
XElement contacts=new XElement("学生列表",
new XElement("详细资料",
new XElement("姓名","王二"),
new XElement("年龄","23"),
new XElement("电话"15:51 2011-4-21,"13888888888",
new XAttribute("类型","移动电话")),
new XElement("电话","87878787",
new XAttribute("类型","家长联系电话")),
new XElement("成绩",
new XElement("语文","88"),
new XElement("历史","91"),
new XElement("政治","70")
)
)
);
// 保存到XML文件中
contacts.Save(Server.MapPath("students.xml"));
}
protected void btncreatXML_click(object sender, EventArgs e)
{
//判断是否已经存在同名文件,如果不存在则进行下面的操作
if (!File.Exists(Server.MapPath("students.xml")))
{
CreateXML(); //调用此方法进行创建和保存
//创建后如果存在,则证明创建成功
if (File.Exists(Server.MapPath("students.xml")))
{
Response.Write("创建成功!"); //输出信息成功
}
}
else //如果已存在
{
Response.Write("保存失败:同名文件已存在!");
}
}
protected void btnqueryall_click(object sender, EventArgs e)
{
XElement exl = XElement.Load(Server.MapPath("People.XML")); //加载XML文件
var c = from x in exl.Descendants("People") //linq查询
select x; //遍历结果
foreach (var cc in c)
{
Response.Write(cc.ToString() + "<br>"); //输出
}
}
protected void btnquery_click(object sender, EventArgs e)
{
XElement exl = XElement.Load(Server.MapPath("People.xml")); //加载XML文件
var c = from x in exl.Descendants("People") //linq查询
where (string)x.Element("ProductID") == "1"
select x; //遍历结果
foreach (var cc in c)
{
Response.Write(cc.ToString() + "<br>"); //输出
}
}
<?XML version="1.0" standalone="yes"?>
<NewDataSet>
<Product>
<ProductID>1</ProductID>
<ProductName>chai</ProductName>
<UnitPrice>18.00000</UnitPrice>
<QuantityPerUint>10 boxes 20 bags</QuantityPerUint>
<UnitsInStock>39</UnitsInStock>
<UnitsOnOrder>0</UnitsOnOrder>
</Product>
<Product>
<ProductID>2</ProductID>
<ProductName>chang</ProductName>