【发布时间】:2016-09-06 09:08:32
【问题描述】:
我是 C# 新手,我正在尝试将数据从 xml 加载到带有文本和值的组合框项目 我的xml结构
<?xml version="1.0" encoding="UTF-8"?>
<roomsgg id="1">
<rooms id="1">
<roomtype id="1" name="standard">
<roomtimeprice id="5">
<rtid>5</rtid>
</roomtimeprice>
<roomtimeprice id="6">
<rtid>6</rtid>
</roomtimeprice>
</roomtype>
<roomtype id="2" name="sweet">
<roomtimeprice id="7">
<rtid>7</rtid>
</roomtimeprice>
<roomtimeprice id="8">
<rtid>8</rtid>
</roomtimeprice>
<roomtimeprice id="9">
<rtid>9</rtid>
</roomtimeprice>
</roomtype>
<roomtype id="3" name="gfgfgfgfgfgf">
<roomtimeprice id="10">
<rtid>10</rtid>
</roomtimeprice>
<roomtimeprice id="11">
<rtid>11</rtid>
</roomtimeprice>
<roomtimeprice id="12">
<rtid>12</rtid>
</roomtimeprice>
</roomtype>
</rooms>
</roomsgg>
我想用房间类型文本填充组合框并将 id 设置为项目的值
public class ComboboxItem
{
public string Text { get; set; }
public string Value { get; set; }
public override string ToString()
{
return Text;
}
}
public frmChangeRoom(string hotel_id2)
{
InitializeComponent();
hotel_id3 = hotel_id2;
fillCombo();
}
//view data select type rooms
void fillCombo()
{
string mvalue = "1";
XDocument readrooms = XDocument.Load("http://www.website.com/api/api.php?action=getrooms&hotel_id=" + hotel_id3);
var mnodes = (from z in readrooms.Descendants("rooms").Where(e => e.Parent.Attribute("id").Value == mvalue)
select new
{
roomtypemainid = (string)z.Element("roomtype").Attribute("id").Value,
roomtypemainname = (string)z.Element("roomtype").Attribute("name").Value
}).ToList();
foreach (var z in mnodes)
{
ComboboxItem itemz = new ComboboxItem();
itemz.Text = z.roomtypemainname;
itemz.Value = z.roomtypemainid;
sel_typeRoom.Items.Add(itemz);
}
问题是只有第一个想要的元素出现,这是标准的 有什么想法吗?
解决了:
XDocument readrooms = XDocument.Load("http://www.website.com/api/api.php?action=getrooms&hotel_id=" + hotel_id3);
readrooms.Descendants("roomtype").Select(p => new
{
roomtypename = p.Attribute("name").Value,
roomtypeid = p.Attribute("id").Value
}).ToList().ForEach(p =>
{
ComboboxItem itemz = new ComboboxItem();
itemz.Text = p.roomtypename;
itemz.Value = p.roomtypeid;
sel_typeRoom.Items.Add(itemz);
});
【问题讨论】:
-
将它们转换成
DataTable并赋值给ComboBox -
代码读取第一个结果为什么不是所有结果?
-
因为您的
XML架构看起来像是将它们分成 4 个表.. -
谢谢...问题解决了