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

发布于 2024-10-18 04:55:27 字数 1035 浏览 5 评论 0 原文

我有一个包含 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 本身,则会失败。示例:如果值类似于

<?xml version="1.0" encoding="utf-8"?><GetCashFlow xmlns="MyServices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></GetCashFlow>

It 错误并显示消息:

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

如果您认为 xml 格式可以使存储在 Dictionary 对象中变得更容易,请随时建议对 xml 格式进行任何修改。

I have a string containing field/value pairs in xml format and want to parse it into Dictionary object.

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

Is there a quick and simple way to read and store all the field/value pairs in Dictionary object? No LINQ please.

Also, there could be possibility that the value field can contain an xml string itself. the solutions provided is wonderful but fails if the value is xml iteself. Example: If the value is something like

<?xml version="1.0" encoding="utf-8"?><GetCashFlow xmlns="MyServices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></GetCashFlow>

It errors out with the message:

Unexpected XML declaration. The XML
declaration must be the first node in
the document, and no white space
characters are allowed to appear
before it.

Please feel free to suggest any modification in xml format if you think it can make things easier to store in Dictionary object.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

惯饮孤独 2024-10-25 04:55:27
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);
            }
        }
    }
}
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);
            }
        }
    }
}
山色无中 2024-10-25 04:55:27

使用 LINQ 将数据放入字典非常简单:

XDocument d = XDocument.Parse(xml);
Dictionary<string, string> dict = d.Descendants("fieldvaluepair")
   .Where(x => x.Descendants("field").FirstOrDefault() != null 
               && x.Descendants("value").FirstOrDefault() != null)
   .ToDictionary(x => x.Descendants("field").First().Value,
                 x => x.Descendants("value").First().Value);

如果您非常确信您的 fieldvaluepair 元素都具有 fieldvalue 子级,您可以省略 Where 调用。

如果value元素可以包含非文本内容,问题就更复杂了。第一个问题是:您需要创建一个Dictionary,还是一个Dictionary>?也就是说,每个字典条目的值是否应包含 value 元素的内部 XML 作为字符串,或者是否应包含作为 value 子级的所有节点元素?

如果是前者,则需要将值函数更改为:

x => string.Join("", x.Descendants("value").First()
                      .Descendants().ToString()
                      .ToArray()

将所有后代节点的字符串值连接在一起。如果是后者,只需执行:

x => x.Descendants("value").Descendants()

也就是说,您在问题中描述的情况,其中 value 元素包含字符串:

<?xml version="1.0" encoding="utf-8"?><GetCashFlow xmlns="MyServices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></GetCashFlow>

不是格式良好的 XML。如果创建您正在解析的字符串的过程正在生成该字符串,则需要对其进行修复,以便它使用 XML 库来生成 XML,而不是字符串连接。

Getting the data into a dictionary is simple enough using LINQ:

XDocument d = XDocument.Parse(xml);
Dictionary<string, string> dict = d.Descendants("fieldvaluepair")
   .Where(x => x.Descendants("field").FirstOrDefault() != null 
               && x.Descendants("value").FirstOrDefault() != null)
   .ToDictionary(x => x.Descendants("field").First().Value,
                 x => x.Descendants("value").First().Value);

If you've got a high degree of confidence that your fieldvaluepair elements all have field and value children, you can omit that Where call.

If the value element can contain non-text content, the problem is more complicated. The first question is: do you need to create a Dictionary<string, string>, or a Dictionary<string, IEnumerable<XNode>>? That is, should the value of each dictionary entry contain the inner XML of the value element as a string, or should it contain all of the nodes that are children of the value element?

If it's the former, you need to change the value function to:

x => string.Join("", x.Descendants("value").First()
                      .Descendants().ToString()
                      .ToArray()

which concatenates together the string value of all of the descendant nodes. If it's the latter, just do:

x => x.Descendants("value").Descendants()

That said, the case that you describe in your question, where the value element contains the string:

<?xml version="1.0" encoding="utf-8"?><GetCashFlow xmlns="MyServices"><inputparam><ac_unq_id>123123110</ac_unq_id></inputparam></GetCashFlow>

is not well-formed XML. If the process that creates the string you're parsing is producing that, it needs to be fixed so that it uses an XML library to produce XML instead of string concatenation.

百思不得你姐 2024-10-25 04:55:27

我描述了一个片段,它展示了如何读取 XML 内容并将其放入字典中。请记住,这不是处理它的最佳方法,因为这种技术是一步一步的,因此,如果您有一个非常复杂的 xml 结构,那么管理起来将非常困难。但对于你的情况,它也可以使用。我没有使用 LINQ maner (更好的形式)来回答你的请求。希望大家可以使用或者尝试修改以获得更好的结果。有什么问题再在这里发帖吧。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace XMLReader
{
/// <summary>
/// Author: Inocêncio T. de Oliveira
/// Reader a XML file and put all content into a Dictionary
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        //the source of the XML
        XmlTextReader reader = new XmlTextReader("c:\\myxml.xml");
        //dictionary to be filled
        Dictionary<string, string> dic = new Dictionary<string, string>();
        //temporary variable to store the field value
        string field = "";
        int count = 0;

        //reading step thru the XML file
        while (reader.Read())
        {
            XmlNodeType nt = reader.NodeType;

            if (nt == XmlNodeType.Text)
            {
                //Console.WriteLine(reader.Name.ToString());
                if (count == 0)
                {
                    //store temporarily the field value
                    field = reader.Value.ToString();
                    count++;
                } else if (count == 1)
                {
                    //add a new entry in dictionary
                    dic.Add(field, reader.Value.ToString());
                    count = 0;
                }
            }
        }

        //we done, let´s check if datas are OK stored!

        foreach (KeyValuePair<string, string> kvp in dic)
        {
            Console.WriteLine("field [{0}] : value [{1}]", kvp.Key, kvp.Value);
        }

        Console.ReadKey();
    }
}
}

I describe a snippet that show how to read a XML content and put it into a Dictionary. Remember that is not the best way to handle it, because this technic is step-by-step, so, if you have a very complex xml structure that maner will be bery difficult to manager. But for your case it can be used as well. I did it without using LINQ maner (better form) to answer your request. I hope you can use it or try to modify to get a better result. Any question post here again.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace XMLReader
{
/// <summary>
/// Author: Inocêncio T. de Oliveira
/// Reader a XML file and put all content into a Dictionary
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        //the source of the XML
        XmlTextReader reader = new XmlTextReader("c:\\myxml.xml");
        //dictionary to be filled
        Dictionary<string, string> dic = new Dictionary<string, string>();
        //temporary variable to store the field value
        string field = "";
        int count = 0;

        //reading step thru the XML file
        while (reader.Read())
        {
            XmlNodeType nt = reader.NodeType;

            if (nt == XmlNodeType.Text)
            {
                //Console.WriteLine(reader.Name.ToString());
                if (count == 0)
                {
                    //store temporarily the field value
                    field = reader.Value.ToString();
                    count++;
                } else if (count == 1)
                {
                    //add a new entry in dictionary
                    dic.Add(field, reader.Value.ToString());
                    count = 0;
                }
            }
        }

        //we done, let´s check if datas are OK stored!

        foreach (KeyValuePair<string, string> kvp in dic)
        {
            Console.WriteLine("field [{0}] : value [{1}]", kvp.Key, kvp.Value);
        }

        Console.ReadKey();
    }
}
}
巴黎盛开的樱花 2024-10-25 04:55:27

您可以使用 System.Xml.XmlReader 来解析 xml。对于像您的示例中这样的简单结构,这非常有效。对于更复杂的 xml 结构,下面的方法可能会变得丑陋。

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>";
var reader = XmlReader.Create(new StringReader(param));
var dictionary = new Dictionary<string, string>();
reader.ReadStartElement();
while (reader.NodeType != System.Xml.XmlNodeType.EndElement) {
    reader.ReadStartElement("fieldvaluepair");
    reader.ReadStartElement("field");
    string key = reader.ReadString();
    reader.ReadEndElement();
    reader.ReadStartElement("value");
    string value = reader.NodeType == XmlNodeType.Element 
        ? reader.ReadOuterXml() : reader.ReadString();
    reader.ReadEndElement();
    dictionary.Add(key, value);
    reader.ReadEndElement();
}
reader.ReadEndElement();
reader.Close();

编辑:在上面的代码示例中,我正在处理该值可以包含 xml 和文本的事实。不过,没有进一步解析此 xml,它只是作为字符串存储在字典中。对于“field”元素也可以做同样的事情。

You can use System.Xml.XmlReader to parse the xml. This works quite ok with a simple structure like in your example. For more complex xml structures, the approach below could turn ugly.

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>";
var reader = XmlReader.Create(new StringReader(param));
var dictionary = new Dictionary<string, string>();
reader.ReadStartElement();
while (reader.NodeType != System.Xml.XmlNodeType.EndElement) {
    reader.ReadStartElement("fieldvaluepair");
    reader.ReadStartElement("field");
    string key = reader.ReadString();
    reader.ReadEndElement();
    reader.ReadStartElement("value");
    string value = reader.NodeType == XmlNodeType.Element 
        ? reader.ReadOuterXml() : reader.ReadString();
    reader.ReadEndElement();
    dictionary.Add(key, value);
    reader.ReadEndElement();
}
reader.ReadEndElement();
reader.Close();

EDIT: In the code example above, I'm handling the fact that the value could contain xml as well as text. There is no further parsing of this xml, though, and it is just stored as a string in the dictionary. The same could be done for the 'field' element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文