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

标签 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>";


有没有一种快速简单的方法来在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>


错误消息:


  意外的XML声明。 XML
  声明必须是中的第一个节点
  文档,没有空格
  允许出现字符
  在它之前。


如果您认为xml格式的修改可以使事情更容易存储在Dictionary对象中,请随时提出建议。

最佳答案

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);
            }
        }
    }
}

关于c# - 在C#中将xml字符串(字段/值对)解析为Dictionary对象的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5032741/

相关文章:

javascript - textContent 未读取所有文本

python : Can Dictionary be used for indexing?

python - Pandas:如何将字典映射到 2 列?

C# 将 Action<int> 转换为 lambda

c# - ConfigureAwait(false) 没有按预期使 HttpContext NULL

c# - WPF 多个 ItemSource?

c# - API架构

xml - XPath选择所有同级和子节点,直到下一个自封闭元素的下一次出现

java - 为什么我的 toast 不起作用? (安卓)

swift - Swift 3 中保存泛型键的特定泛型类型的字典