首页 新闻 赞助 找找看

求用Lambda表达式将xml文件读入Dictionary的代码

0
悬赏园豆:20 [已关闭问题] 关闭于 2016-09-06 10:27

因刚学习C#,练习用xml文件存储数据遇到难题,特来向高手求助将xml文件读取到Dictionary,xml样式如下:

复制代码
<进货>
  <进货日期 ID="0001" 日期="20160828">
      <商品 A="aa" B="bb" C="cc" D="dd" E="ee" F="ff" G="gg"/>
  </进货日期>
  <进货日期 ID="0002" 日期="20160829">
      <商品 A="aa" B="bb" C="cc" D="dd" E="ee" F="ff" G="gg"/>
  </进货日期>
</进货>
复制代码

用Lambda表达式读取到Dictionary后的效果如下代码段的Dic集合:

var Dic = new Dictionary<KeyValuePair<int, int>, string>();
            Dic.Add(new KeyValuePair<int, int>(0, 0), "aa");
            Dic.Add(new KeyValuePair<int, int>(0, 1), "bb");
            Dic.Add(new KeyValuePair<int, int>(0, 2), "cc");
            Dic.Add(new KeyValuePair<int, int>(1, 0), "aa");
            Dic.Add(new KeyValuePair<int, int>(1, 1), "bb");
            Dic.Add(new KeyValuePair<int, int>(1, 2), "cc");

 

从数据库读取成功,可是读xml搞了好久就是没成功,望高手指点。

问题补充:

求园子里的高手帮忙解决

梦天涯的主页 梦天涯 | 初学一级 | 园豆:103
提问于:2016-09-01 18:00
< >
分享
所有回答(3)
0

上代码或者截图,看问题出在哪里

balahoho | 园豆:2050 (老鸟四级) | 2016-09-01 19:56
0

这谁知道你是怎么读的啊。。。

顾晓北 | 园豆:10844 (专家六级) | 2016-09-02 08:54
0

根据你提供的xml字符串写的代码Demo,可以正常读取,供参考:

                /*
                < 进货 >
                    < 进货日期 ID = "0001" 日期 = "20160828" >
                        < 商品 A = "aa" B = "bb" C = "cc" D = "dd" E = "ee" F = "ff" G = "gg" />
                    </ 进货日期 >
                    < 进货日期 ID = "0002" 日期 = "20160829" >
                        < 商品 A = "aa" B = "bb" C = "cc" D = "dd" E = "ee" F = "ff" G = "gg" />
                    </ 进货日期 >
                </ 进货 >
                */
                string strXml = textBox1.Text.Trim();
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(strXml); //加载xml字符串

                Dictionary<KeyValuePair<string, string>, string> dic = new Dictionary<KeyValuePair<string, string>, string>();
                //得到根节点
                XmlNodeList xnList = xmlDoc.SelectNodes("进货");
                foreach (XmlNode item in xnList) //循坏节点
                {
                    XmlNodeList cndList = item.ChildNodes;
                    foreach (XmlNode item1 in cndList)
                    {
                        
                        string id = item1.Attributes.GetNamedItem("ID").Value;
                        string date = item1.Attributes.GetNamedItem("日期").Value;
                        string a = item1.FirstChild.Attributes.GetNamedItem("A").Value; //获取商品子节点属性A的值
                        dic.Add(new KeyValuePair<string, string>(id, date), a); //将指定的键和值添加到字典中
                    }
                }

 

雨之秋水 | 园豆:649 (小虾三级) | 2016-09-02 11:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册