gpt4 book ai didi

c# 将 xml 加载到组合框中

转载 作者:太空宇宙 更新时间:2023-11-03 15:14:57 25 4
gpt4 key购买 nike

我是 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);

});

最佳答案

问题是您选择的元素只有其中之一:"rooms" . descendants 方法不返回您提供的元素的后代列表,而是返回该类型的后代元素列表。

像这样更改您的链接:(看到 select 已经创建了您的自定义类型)

XDocument readrooms = XDocument.Load("http://www.wiseuo.com/api/api.php?action=getrooms&hotel_id=" + hotel_id3);
var mnodes = (from x in readrooms.Descendants("roomsgg")
where x.Attribute("Id").Value == mvalue
from z in x.Descendants("roomtype")
select new ComboboxItem
{
Value = (string)z.Attribute("id").Value,
Text = (string)z.Attribute("name").Value
}).ToList();

parent 上添加您的选择用于检查 id 的元素然后获取它下面的所有项目就像使用 SelectMany方法语法中的方法

关于c# 将 xml 加载到组合框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39344988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com