c# - 如何在 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 类型。
我想从响应中提取所有记录的列表。我不确定如何编写代码来过滤数据。
请为此参考一些样本。
解决方案
这是获取值的一种快速而肮脏的方法,可以通过删除硬编码值并在访问它们之前检查对象来改进。
编辑: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("----------------------------------");
}
}
}
推荐阅读
- python - Python从给定的txt文件创建字典
- unit-testing - MarkLogic 单元测试未运行任何测试
- algorithm - 在未加权图中找到最长的路径
- python - 数据输出和内部函数不一样
- javascript - 从属性数组中搜索 Javascript 对象并将它们与一个值进行比较
- regex - 正则表达式 - 阅读直到第一次遇到冒号 (:) 并忽略该行的其余部分和开头的数字部分
- c# - 您如何允许文本框为空或 5 位数字
- aws-lambda - DocuSign 通过 AWS Lambda 嵌入 UI
- sql - PostgreSQL 的时间戳差异(以分钟为单位)
- sql - 创建了这个过程,当我执行时我没有得到预期的结果