【问题标题】:Confusion about reading xml file关于读取xml文件的困惑
【发布时间】:2013-12-25 16:11:51
【问题描述】:
我正在尝试从我的 xml 文件中检索一些数据到列表视图。我有点困惑。这是我到目前为止所拥有的。怎么做。提前致谢
XDocument doc=XDocument.Load(Server.MapPath("PhoneBook.xml"));
var q = from c in doc.Descendants("Persons") select new
{
name=c.Element("Name"),
phone=c.Element("Phone"),
};
foreach (var item in q)
{
var lvi = new ListViewItem(item.name);
}
【问题讨论】:
标签:
asp.net
linq
listview
【解决方案1】:
您的代码的第一部分看起来不错。您不需要 foreach 循环。你的代码应该是这样的:
XDocument doc = XDocument.Load(Server.MapPath("PhoneBook.xml"));
var q = from c in doc.Descendants("Persons")
select new
{
name = c.Element("Name"),
phone = c.Element("Phone"),
};
ListView1.DataSource = q;
ListView1.DataBind();
在标记中,您可以将任何模板字段与姓名或电话绑定。您的 ListView 可能如下所示:
<asp:ListView runat="server" ID="ListView1">
<LayoutTemplate>
<table runat="server" id="table1">
<tr runat="server" id="itemPlaceholder">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<asp:Label ID="NameLabel" runat="server"
Text='<%#Eval("Name") %>' />
</td>
<td id="Td2" runat="server">
<asp:Label ID="PhoneLabel" runat="server"
Text='<%#Eval("Phone") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
而且这种布局会产生这种类型的输出:
希望对你有帮助!
【解决方案2】:
如果没有示例 XML,很难预测,但我注意到您缺少“根”元素,因此下一个要导航的项目是“根:”内的元素:
XDocument doc=XDocument.Load(Server.MapPath("PhoneBook.xml"));
var items = (from item in doc.Root.Elements("Persons")
select new {
name=c.Element("Name"),
phone=c.Element("Phone"),
};
如果这不是答案,请分享您的 XML 示例,这将有助于我们提供更好的答案。
【解决方案3】:
首先像这样更改您的代码,因为您将 Name 和 Phone 分配给 XElement,而不是 Element Value:
var q = from c in doc.Descendants("Persons")
select new {
name=c.Element("Name").Value,
phone=c.Element("Phone").Value
};
然后试试这个代码:
listView1.View = View.Details;
listView1.Columns.Add("Person Name", 200, HorizontalAlignment.Left);
listView1.Columns.Add("Phone Number", 100, HorizontalAlignment.Left);
foreach (var item in q)
{
ListViewItem listItem = new ListViewItem();
listItem.Text = item.Name;
listItem.SubItems.Add(item.Phone);
listView1.Items.Add(listItem);
}