【发布时间】:2014-11-04 17:02:52
【问题描述】:
尝试将 xml 文档解析为我创建的自定义类。我已经成功地弄清楚了如何解析文档,但由于某种原因,我不得不将其转换为 IEnumerable 而不仅仅是我的自定义类的单个实例。仅显示代码比深入解释容易得多,因此请参阅下面的代码 sn-ps。
工作代码
IEnumerable<Ping> ping = xmlDoc.Descendants("PING_SEND").Select(p => new Ping
{
TRAN_ID = (string)p.Element("TRAN_ID"),
MILOC = (string)p.Element("MILOC"),
TRANDATE = (string)p.Element("TRANDATE"),
TRANTIME = (string)p.Element("TRANTIME"),
COUNTRY = (string)p.Element("COUNTRY")
});
这导致不得不使用...
foreach (Ping p in ping)
{
cmd.Parameters.AddWithValue("@TRAN_ID", p.TRAN_ID);
cmd.Parameters.AddWithValue("@MILOC", p.MILOC);
cmd.Parameters.AddWithValue("@SITE_REF", "");
}
... 添加要插入数据库的参数时。我尝试过(并且需要)的是更符合这一点的东西......
所需的代码想法
Ping ping =(Ping)xmlDoc.Descendants("PING_SEND").Select(p => new Ping
{
TRAN_ID = (string)p.Element("TRAN_ID"),
MILOC = (string)p.Element("MILOC"),
TRANDATE = (string)p.Element("TRANDATE"),
TRANTIME = (string)p.Element("TRANTIME"),
COUNTRY = (string)p.Element("COUNTRY")
});
//... Other operations and database functions...
cmd.Parameters.AddWithValue("@TRAN_ID", ping.TRAN_ID);
cmd.Parameters.AddWithValue("@MILOC", ping.MILOC);
cmd.Parameters.AddWithValue("@SITE_REF", "");
【问题讨论】: