【发布时间】:2016-10-06 02:49:09
【问题描述】:
在下面的代码中,我希望使用 XML 文件完成我创建的对象的属性:
private void btnLoadRooms_Click(object sender, EventArgs e)
{
try
{
string filePath = string.Empty;
OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file
if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user
{
filePath = file.FileName;
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList RoomTypesList = doc.SelectNodes("/Room_Types/table1_Group1_Collection/table1_Group1_ Hotel_Long_NM_1/table1_Group2_Collection");
List<RoomTypes> lista = new List<RoomTypes>();
RoomTypes RT = new RoomTypes();
foreach(XmlNode xn in RoomTypesList)
{
RT = new RoomTypes();
RT.bedding = xn["Bed_Qty_Cd_1"].InnerText;
RT.bedding += " ";
RT.bedding += xn["Bed_Typ_Desc_1"].InnerText;
RT.guest = xn["Guest_Limit_1"].InnerText;
RT.roomCode = xn["Rm_Typ_CD"].InnerText;
RT.roomName = xn["Rm_Typ_NM_1"].InnerText;
}
lblError.Text = "Room types loaded.";
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
这是具有不同节点的 XML 文件。调试后我可以看到其中一个节点在酒店后面有一个空间:
able1_Group1_Hotel_Long_NM_1如果我在酒店之前删除空间,则不会出现无效令牌错误,但节点列表为空。
<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="RoomTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="RoomTypes" xsi:schemaLocation="RoomTypes http://shprltxrpweb01.sgdcprod.sabre.com/ReportServer?%2FRedX_Reports%2FRoomTypes&rs%3ACommand=Render&rs%3AFormat=XML&rs%3ASessionID=nhe3flbhhs30yd2uj3vfw355&rc%3ASchema=True">
<Room_Types>
<table1_Group1_Collection>
<table1_Group1 Hotel_Long_NM_1="New Cumberland Hotel">
<table1_Group2_Collection>
<table1_Group2 Rm_Typ_Level="Hotel Level" Rm_Typ_NM_1="No Smoking Room with One King Bed Access" Rm_Typ_CD="HNK">
<table1_Group3_Collection>
<table1_Group3>
<Detail_Collection>
<Detail Component_Suite="No" Rolling_Inventory="0" Rm_Typ_Grp_Nm_And_Level="HNK (Chain Level)" Default_Room_Supplement="+0.00 USD" Rm_Typ_Qty_1="5" Guest_Limit_1="2" Rm_Class_Desc_1="Handicap Access" Bed_Qty_Cd_1="1" Bed_Typ_Desc_1="King" Default_Rm_Typ_Short_Desc_1="No Smoking Room with One King Bed Accessible." PMS_Rm_Typ_CD_1="HNK" Hotel_Rm_Serv_CD_1=" ()" Extra_Long_Description="() Extra Long Description:" Long_Description="() Long Description:" Short_Description="() Short Description:"/>
</Detail_Collection>
</table1_Group3>
<table1_Group3 Type="Channel Description(s):">
【问题讨论】:
-
你真的不应该这样做
catch (Exception ex)- blogs.msdn.microsoft.com/ericlippert/2008/09/10/… -
如果您已经解决了 XPath 无效令牌错误,为什么不将问题的标题更新为最新的?
-
没有名为
table1_Group1_ Hotel_Long_NM_1的元素。它的名字是table1_Group1。它有一个名为Hotel_Long_NM_1的属性。您可以将Hotel_Long_NM_1留在 XPath 之外。 -
@kjhughes 他/她并没有真正解决它,只是找到了一种让它停止出现的方法。
-
@JLRishe:承认,只是意味着标题应该反映当前问题,而不是过去,(已解决)问题的一部分。 (OP有多个问题,至少包括what you've pointed out 和what I've pointed out。)