在C#中将xml字符串(字段/值对)解析为Dictionary对象的快速方法

Sri*_*ddy 1 c# xml dictionary xml-parsing

我有一个包含xml格式的字段/值对的字符串,并希望将其解析为Dictionary对象.

string param = "<fieldvaluepairs>
<fieldvaluepair><field>name</field><value>books</value></fieldvaluepair>
<fieldvaluepair><field>value</field><value>101 Ways to Love</value></fieldvaluepair>
<fieldvaluepair><field>type</field><value>System.String</value></fieldvaluepair>
</fieldvaluepairs>";
Run Code Online (Sandbox Code Playgroud)

是否有一种快速简单的方法来读取和存储Dictionary对象中的所有字段/值对?请不要LINQ.

此外,值字段可能包含xml字符串本身.提供的解决方案很精彩,但如果值为xml iteself则会失败.示例:如果值类似于

<?xml version="1.0" encoding="utf-8"?><GetCashFlow xmlns="MyServices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></GetCashFlow>
Run Code Online (Sandbox Code Playgroud)

它错误地显示消息:

意外的XML声明.XML声明必须是文档中的第一个节点,并且不允许在其前面显示空白字符.

如果您认为它可以更容易存储在Dictionary对象中,请随意建议以xml格式进行任何修改.

Jim*_*dra 5

using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Collections.Generic;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><r><a><k>key1</k><v><![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?><foo><bar>Hahaha</bar></foo>]]></v></a><a><k>key2</k><v>value2</v></a></r>";

             PrintDictionary(XmlToDictionaryLINQ(xml));
             PrintDictionary(XMLToDictionaryNoLINQ(xml));
        }

        private static Dictionary<string, string> XMLToDictionaryNoLINQ(string xml)
        {
            var doc = new XmlDocument();
            doc.LoadXml(xml);

            var nodes = doc.SelectNodes("//a");

            var result = new Dictionary<string, string>();
            foreach (XmlNode node in nodes)
            {
                result.Add(node["k"].InnerText, node["v"].InnerText);
            }

            return result;
        }

        private static Dictionary<string, string> XmlToDictionaryLINQ(string xml)
        {
            var doc = XDocument.Parse(xml);
            var result =
                (from node in doc.Descendants("a")
                 select new { key = node.Element("k").Value, value = node.Element("v").Value })
                .ToDictionary(e => e.key, e => e.value);
            return result;
        }

        private static void PrintDictionary(Dictionary<string, string> result)
        {
            foreach (var i in result)
            {
                Console.WriteLine("key: {0}, value: {1}", i.Key, i.Value);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)