【发布时间】:2012-10-21 17:06:25
【问题描述】:
我使用以下 C# 代码通过 JSON.Net 框架将 JSON 数据字符串转换为动态对象:
// Creates a dynamic .Net object representing the JSON data
var ProductDB = JsonConvert.DeserializeObject<dynamic>(JsonData);
转换后,我可以使用如下代码直接访问元素:
// Variables to be used
string ProductID;
string ProductType;
int ProductQty;
// Loop through each of the products
foreach (dynamic product in ProductDB.products)
{
ProductID = product.id;
ProductType = product.type;
ProductQty = product.qty;
}
在处理 XML 数据时有什么类似的东西吗?我可以使用 JSON.net 将我的 XML 转换为 JSON,然后重新使用上面的代码,但这感觉像是在作弊。
谢谢。
【问题讨论】:
-
我根据您的要求找到了一些不错的解决方案:1.Parse XML to dynamic object in C# 2.Creating a dynamic object from XML using ExpandoObject 3.Fluent XML Parsing Using C#'s Dynamic Type Part 1 4.[带有 C# 和 .Net 4.0 的动态 XML 阅读器](@ 987654324@