C# 将XML字符串API响应转换为键值对象C

C# 将XML字符串API响应转换为键值对象C,c#,xml,C#,Xml,我从和API收到一个XML字符串,希望将这些字符串转换为C对象的键值,以便处理这些值并应用一些断言 消息的格式为字符串格式: <?xml version="1.0" encoding="UTF-8"?> <ReportData> <ProjectName>Test Data</ProjectName> <Unit>Unit 1</Unit> <ReportLab

我从和API收到一个XML字符串,希望将这些字符串转换为C对象的键值,以便处理这些值并应用一些断言

消息的格式为字符串格式:

<?xml version="1.0" encoding="UTF-8"?>
<ReportData>
   <ProjectName>Test Data</ProjectName>
   <Unit>Unit 1</Unit>
   <ReportLabel.Cost>394</ReportLabel.Cost>
</ReportData>
在这一点上,我有和xml,但我不能得到一个键值对象

我正在努力

var jsonText = JsonConvert.SerializeXmlNode(doc);


我不熟悉XML中的这种响应,不确定执行这种响应的方式。它不像JSON格式那么简单。

您不能直接将xml转换为dict的键值对,相反,我们需要迭代xml中的每个节点,并将其作为键值对添加到dict对象中

请参阅

您可以使用System.Xml.Linq执行此任务。 以下是从XML创建字典的一种方法:

static void Main(string[] args)
{
    // or use other overload of the Load() method if the XML is not comes from a file stream, uri etc...
    var xmldoc = System.Xml.Linq.XDocument.Load("YOUR FILE PATH");

    Dictionary<string, string> XMLKeyval = new Dictionary<string, string>();
    foreach (var name in xmldoc.Descendants("ReportData").Elements()
                        .Select(x => new { Name = x.Name, Value = x.Value }).Distinct())
    {
        XMLKeyval.Add(name.Name.LocalName, name.Value);
    }

    // Output
    foreach (KeyValuePair<string, string> itm in XMLKeyval)
    {
        Console.WriteLine(itm.Key + ": " + itm.Value);
    }

    Console.ReadLine();
}

这是一个XML,您不能使用JSONConvert。这是否回答了您的问题?如果您觉得链接的答案回答了这个问题,请将其标记为副本。
serializer = new XmlSerializer(typeof(Object));
using (TextReader reader = new StringReader(responseAPI))
{
  var result = (Object)serializer.Deserialize(reader);
}
var response = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseAPI);
static void Main(string[] args)
{
    // or use other overload of the Load() method if the XML is not comes from a file stream, uri etc...
    var xmldoc = System.Xml.Linq.XDocument.Load("YOUR FILE PATH");

    Dictionary<string, string> XMLKeyval = new Dictionary<string, string>();
    foreach (var name in xmldoc.Descendants("ReportData").Elements()
                        .Select(x => new { Name = x.Name, Value = x.Value }).Distinct())
    {
        XMLKeyval.Add(name.Name.LocalName, name.Value);
    }

    // Output
    foreach (KeyValuePair<string, string> itm in XMLKeyval)
    {
        Console.WriteLine(itm.Key + ": " + itm.Value);
    }

    Console.ReadLine();
}