首页 > 解决方案 > 如何在 C# 中使用 foreach 从 XMLElement 中迭代数据

问题描述

我想从 XMLElement 迭代数据。在列表中我有 10 行记录。每行再次包含值列表。在行中,每个值都需要存储为 somString 类型。

下面是从 List 获取的 XMLElement

<ROW id="1">
   <D n="6721">10128</D>
   <D n="6724">CL</D>
   <D n="6771">*</D>
   <D n="6773">ACT</D>
   <D n="6774">PHON</D>
   <D n="6775">04-MAR-2018 21:54</D>
   <D n="6779">MEP-IU</D>
   <D n="6780">MEP-IU-010</D>
   <D n="6782">CWP2B19-113</D>
   <D n="6792">11410</D>
   <D n="6809"/>
   <D n="6880"/>
   <D n="11651">Tap is not working in the Back of the Apt  
                Name: Alex 
                Contact : 971-566826978</D>
   <D n="100410">40977</D>
   <D n="101312">AHMED.ALI@MERAAS.AE</D>
   <D n="101313">HANDOVER</D>
 </ROW>

我尝试了这段代码,因为我试图迭代数据,但我得到的只是第一个元素,而不是剩余的元素:

for (int i = 0; i < nodeList.Count; i++)
{
    if (nodeList[i].InnerText.Length > 0)
    {
        string name =(string) i.FirstChild.Value;                     
        MessageBox.Show(nodeList[i].InnerText);
    }
}

但我只获得归档列值..如何从 XMLElement 获取剩余数据。

在列表中我有 10 行记录。每行再次包含值列表。在行中,每个值都需要存储为 somString 类型。

我想从响应中提取所有记录的列表。我不确定如何编写代码来过滤数据。

请为此参考一些样本。

标签: c#ssismdm

解决方案


这是获取值的一种快速肮脏的方法,可以通过删除硬编码值并在访问它们之前检查对象来改进。

编辑:XML 结构来自这里

            using (var stream = new StreamReader("Response.xml"))
            {
                XDocument doc = XDocument.Load(stream);

                var nodes = doc.Elements().Descendants()
                    .Where(x => x.Name == XName.Get("ROW", "http://schemas.datastream.net/MP_functions/MP0118_GetGridHeaderData_001_Result"));

                foreach (var node in nodes)
                {
                    if (node.FirstAttribute != null)
                    {
                        var firstAttribute = node.FirstAttribute;
                        Console.WriteLine($"{firstAttribute.Name.LocalName} - {firstAttribute.Value}");

                        var children = node.Descendants();
                        if (children.Count() > 0)
                        {
                            foreach (var child in children)
                            {
                                Console.WriteLine($"{child.FirstAttribute.Value}:{child.Value}");
                            }
                        }
                        Console.WriteLine("----------------------------------");
                    }
                }
            }

推荐阅读