c# - 在 C# 中将 XML 字符串解析为 List/DataTable
问题描述
我在XML string
下面给出了 2 列no
和Active
XML -
<RECORDS RECORDCOUNT="2">
<RECORD COL_HEADER="0">
<no>201738</no>
<Active>-1</Active>
</RECORD>
<RECORD COL_HEADER="0">
<no>201739</no>
<Active>0</Active>
</RECORD>
</RECORDS>
并将上述内容转换XML string
为list
我尝试Parse
使用以下内容LINQ expression
LINQ - 表达式
var result = XElement.Parse(xmlString)
.Descendants().Where(r => !string.IsNullOrEmpty(r.Value))
.Select(r => int.Parse(r.Value))
.ToList();
错误 -
输入字符串的格式不正确。
在结果集中,我期望两列都有各自的值。我是否必须使用datatable
或除list
.
请帮忙!TIA
解决方案
实际上 <RECORD COL_HEADER="0"> 包含值,你必须添加到你的 Where 一个额外的检查是这样的
Where(r => !string.IsNullOrEmpty(r.Value) && (r.Name == "no" || r.Name == "Active"))
为了获得您的期望,您可以尝试以下操作:
var result = XElement.Parse(xmlString)
.Descendants().
Where(x => x.Name == "RECORD")
.Select(x => new
{
no = int.Parse(x.Element("no").Value),
Active = int.Parse(x.Element("Active").Value)
}
).ToList();
推荐阅读
- spring-boot - Spring Cloud Ribbon 客户端负载均衡器
- reactjs - React typescript 如何在 tsx 中使用类型 useState 和渲染列表
- r - 如何修复“错误:无法分配大小为 265.6 Mb 的向量”
- sqlite - 为什么 sqlite 在使用 create table 时会在任何带有 NULL 的行处停止(之后不再接受任何插入语句)?
- docker - docker-compose 中 ELASTICSEARCH_HOSTS 的语法是什么?
- android - “添加到 FragmentContainerView 的视图必须与 Fragment 关联”与 android Nav 组件
- python - PyTorch、OpenCV 和 NumPy 之后像素颜色略有变化
- python - 用于投资组合 beta 的 groupby 滚动 agg 自定义函数
- php - WooCommerce:将某些类别的价格更改为按重量计算
- python - 为什么使用“min()”会出现此语法错误?