将 XML 转换为动态 C# 对象 [英] Converting XML to a dynamic C# object

查看:47
本文介绍了将 XML 转换为动态 C# 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下 C# 代码将一串 JSON 数据转换为使用 JSON.Net 框架的动态对象:

I've used the following C# code to convert a string of JSON data to a dynamic object using the JSON.Net framework:

// Creates a dynamic .Net object representing the JSON data
var ProductDB = JsonConvert.DeserializeObject<dynamic>(JsonData);

转换后,我可以使用如下代码直接访问元素:

Once converted, I can access the elements directly using code like this:

// 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,然后重新使用上面的代码,但这感觉像是在作弊.

Is there anything similar to this for working with XML data? I could just use JSON.net to convert my XML to JSON and then re-use the code above, but that feels like cheating.

谢谢.

推荐答案

XDocument doc = XDocument.Parse(xmlData); //or XDocument.Load(path)
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);

我认为作弊"就是答案 - xml 解决方案很长 :)

I think "cheating" is the answer - the xml solutions are very long :)

这篇关于将 XML 转换为动态 C# 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆