将XML添加到包含数组C#的字典中

时间:2018-06-21 10:25:48

标签: c# xml dictionary

<status_code>0</status_code>
<status_msg>Success</status_msg> 
<customer_details>
<customer_id>1</customer_id>
<number>99884522</number>
<mobile_number>4562214555</mobile_number>
<customer_name>Test </customer_name>
<balance>457.67</balance>
</customer_details>

</xml>

我想将xml代码添加到字典中,该怎么办?我希望customer_details数组也包含详细信息。

到目前为止,我已经尝试过

            var webResponse = new Dictionary<string, string>();
            XDocument xDoc = XDocument.Parse(xmlfile);// ("filename.xml"); 

            foreach (XElement el in xDoc.Root.Elements())
            {
                if (el.HasElements)
                {
                    webResponse.Add(el.Name.LocalName, el.Value);
                }
                webResponse.Add(el.Name.LocalName, el.Value);

            }

我想要Output int以Json的形式或在字典中

{
    "status_code": 0,
    "status_msg": "Success",

    "customer_details": {
    "customer_id": "1",
    "number": "24234234",
    "mobile_number": "24423423432", 
    "customer_name": "Test ",
    "balance": "467.67"
}

}

1 个答案:

答案 0 :(得分:1)

您可以使用Newtonsoft Json。

 XDocument X = XDocument.Load(@"C:\Users\XMLFile.xml");
 var elements =   X.Elements("xml"); 
     foreach (var item in elements)
        {
            string json = JsonConvert.SerializeXNode(item);
            Console.WriteLine(json);
        }

输出

   {
"xml": {
    "status_code": "0",
    "status_msg": "Success",
    "customer_details": {
        "customer_id": "1",
        "number": "99884522",
        "mobile_number": "4562214555",
        "customer_name": "Test ",
        "balance": "457.67"
    }
}
}

使用的XML是

 <xml>
<status_code>0</status_code>
<status_msg>Success</status_msg>
<customer_details>
  <customer_id>1</customer_id>
  <number>99884522</number>
  <mobile_number>4562214555</mobile_number>
  <customer_name>Test </customer_name>
  <balance>457.67</balance>
</customer_details>
</xml>