我有一个Web应用程序,其中包含一个用于存储用户数据的XML文件。我希望仅在特定用户的网格视图中显示输入的数据,仅基于' txtEmpid.Text'。我认为问题在于字符串阅读器。但我似乎无法弄清楚我是asp.net的新手,这段代码给了我空白页面。 谢谢你的帮助
我的XML文件:
-<SkillSet>
-<SkillSets>
<Employee_ID>1</Employee_ID>
<Employee_Name>abc</Employee_Name>
<PL_Name>xyz</PL_Name>
<Skill_Name1>C# with Asp.NET</Skill_Name1>
<Skill_Type1>Programming</Skill_Type1>
<Skill_Proficiency1>Beginner</Skill_Proficiency1>
<Experience1>1</Experience1>
<Skill_Name2>FL Studio</Skill_Name2>
<Skill_Type2>Others</Skill_Type2>
<Skill_Proficiency2>Intermediate</Skill_Proficiency2>
<Experience2>2</Experience2>
<Skill_Name3>ms word</Skill_Name3>
<Skill_Type3>others</Skill_Type3>
<Skill_Proficiency3>Advance</Skill_Proficiency3>
<Experience3>3</Experience3>
<Skill_Name4>Camtasia</Skill_Name4>
<Skill_Type4>Others</Skill_Type4>
<Skill_Proficiency4>Professional</Skill_Proficiency4>
<Experience4>4</Experience4>
<Skill_Name5>MS excel</Skill_Name5>
<Skill_Type5>Programming</Skill_Type5>
<Skill_Proficiency5>Beginner</Skill_Proficiency5>
<Experience5>5</Experience5>
<Comments>fgfdgdf</Comments>
</SkillSets>
</SkillSet>
这是我的C#文件,它具有绑定数据的逻辑:
private void BindGrid()
{
try {
var xmlStr = File.ReadAllText(Server.MapPath("~/SkillSet.xml"));
var str = XElement.Parse(xmlStr);
var result = str.Elements("SkillSets").
Where(x => x.Element("Employee_ID").Value.Equals(txtEmpid.Text)).ToList();
StringReader theReader = new StringReader(result.ToString());
DataSet ds = new DataSet();
ds.ReadXml(theReader);
if (ds != null && ds.HasChanges())
{
grdxml.DataSource = ds;
grdxml.DataBind();
}
else
{
grdxml.DataBind();
}
}
catch(Exception ex)
{
lblerror.Text = ex.ToString();
}
答案 0 :(得分:0)
试试这个:
string filePath = "Complete path where you saved the XML file";
DataSet ds = new DataSet();
ds.ReadXml(filePath);
var skillSets = ds.Tables[0].AsEnumerable();
var query = from skillset in skillSets
where skillset.Field<string>("Employee_ID") == "1" // here you can get value from text box etc.
select skillset;
grdxml.DataSource = query.ToList();
grdxml.DataBind();
答案 1 :(得分:0)
你的LINQ查询很好。您的代码中存在的问题是:
StringReader theReader = new StringReader(result.ToString());
ds.ReadXml(theReader);
您正在使用result.ToString()
,并且XElements列表的ToString()
表示无法读取为XML。事实上,调用ToString()
将导致此
"System.Collections.Generic.List`1[System.Xml.Linq.XElement]"
正如您所看到的,那不是XML
要使代码正常工作,请尝试以下方法:
try {
var xmlStr = File.ReadAllText(Server.MapPath("~/SkillSet.xml"));
var str = XElement.Parse(xmlStr);
var result = str.Elements("SkillSets").
Where(x => x.Element("Employee_ID").Value.Equals(txtEmpid.Text)).ToList();
grdxml.DataSource = result.ToList();
grdxml.DataBind();
}
catch(Exception ex)
{
lblerror.Text = ex.ToString();
}
另外,删除XML上的斜杠