简体   繁体   English

将System.Collections.Generic.Dictionary转换为XDocument

[英]Turn a System.Collections.Generic.Dictionary into an XDocument

I am trying to make a Dictionary into an XDocument (XML) for easier parsing later in my application. 我试图将一个字典变成一个XDocument(XML),以便以后在我的应用程序中更容易解析。

The application will generate a Word Document based on the XDocument. 应用程序将基于XDocument生成Word文档。 My mate will send me a Dictionary so I have to convert it myself. 我的伴侣会给我一个字典,所以我必须自己转换它。

This is what I got so far, but I am stuck. 这是我到目前为止所得到的,但我被困住了。 I can't really think of how to continue: 我真的不能想到如何继续:

static XDocument Parse(Dictionary<String, String> dic)
    {
        XDocument newXDoc = new XDocument();
        List<String> paragraphs = new List<String>();
        int count = 0;
        foreach(KeyValuePair<string,string> pair in dic)
        {
            if (pair.Key.Equals("paragraph" + count))
            {
                paragraphs.Add(pair.Value);
                count++;
            }
        }
        newXDoc.Add(new XElement("document",
            new XElement("title",dic["title"])));
        return newXDoc;
    }

So to explain: 所以解释一下:

My idea is to make the XML document like this: 我的想法是制作这样的XML文档:

<document>
    <title>Some Title</title>
    <paragraph0>some text</paragraph0>
    <paragraph1>some more text on a new line</paragraph1>
    <paragraph2>
        <list>
            <point>Some Point</point>
            <point>Some other point</point>
        </list>
    </paragraph2>
    <header>
        <author>me</author>
        <date>today</date>
        <subject>some subject</subject>
    </header>
</document>

My problem is that I never know how many paragraphs I will receive given that what I am sent is just a dictionary. 我的问题是,我永远不会知道我会收到多少段,因为我发送的内容只是一本字典。 As you can probably tell, I was pondering over how to make a nice foreach construction which could: 你可能会说,我正在思考如何制作一个漂亮的foreach结构,它可以:

  1. Take out all the Paragraphs temporarily 暂时取出所有段落
  2. Fill in the XDocument with appropriate XElement's 使用适当的XElement填写XDocument

I just don't know how to do this without running into possible NullPointerExceptions or the likes. 我只是不知道怎么做而不遇到可能的NullPointerExceptions或类似的东西。 Any help with this? 对此有何帮助?

Short version: How do I parse a Dictionary to an XDocument given the above structure, not knowing how many paragraphs I can possibly get? 简短版本:在给定上述结构的情况下,如何将字典解析为XDocument,而不知道我可以获得多少段?

A new paragraph is defined as when the previous paragraph reaches a newline character (\\n) 新段落定义为上一段到达换行符时(\\ n)

Using LinqToXML, this will put all dictionary keys starting with "paragraph" into your document: 使用LinqToXML,这将把所有以“paragraph”开头的字典键放入您的文档中:

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

        var dict = new Dictionary<string, string>()
        {
             { "paragraph0", "asdflkj lksajlsakfdj laksdjf lksad jfsadf P0"},
             { "paragraph1", " alkdsjf laksdjfla skdfja lsdkfjadsflk P1"},
             { "paragraph2", "asdflkj lksajlsakfdj laksdjf lksad jfsadf P2"}
        };

        XDocument xd = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), 
            new XElement("document", 
                    dict.Where(kvp => kvp.Key.ToLower().StartsWith("paragraph"))
                        .Select(kvp => new XElement(kvp.Key, kvp.Value)),
                    new XElement("header", "etc")
                )
            );

Well, the first paragraphs could be written like this: 那么,第一段可以这样写:

Dictionary<String, String> dic = new Dictionary<String, String>();
dic.Add("title", "Some Title");
dic.Add("test", "a string");
dic.Add("paragraph0", "some text");
dic.Add("paragraph1", "some more text on a new line");
dic.Add("another test", "a string");
// -----
XDocument newXDoc = new XDocument();
newXDoc.Add(new XElement("document",
              new XElement("title", dic["title"]),
              dic.Where((kvp)=>kvp.Key.StartsWith("paragraph")).Select((kvp)=>new XElement("paragraph", dic[kvp.Key]))));

String s=newXDoc.ToString();
Console.WriteLine(s);

However, the third paragraph depends on your input. 但是,第三段取决于您的输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.Collections.Generic.Dictionary =终极表现? - System.Collections.Generic.Dictionary = Ultimate performance? System.Collections.Generic.Dictionary foreach顺序 - System.Collections.Generic.Dictionary foreach order 反序列化 System.Collections.Generic.Dictionary - deserializing System.Collections.Generic.Dictionary &#39;System.Collections.Generic.Dictionary的最佳重载方法匹配 <int,System.Collections.Generic.Dictionary<string,int> &gt; .Dictionary(int)&#39; - The best overloaded method match for 'System.Collections.Generic.Dictionary<int,System.Collections.Generic.Dictionary<string,int>>.Dictionary(int)' 通过for语句循环通过System.Collections.Generic.Dictionary - Loop through System.Collections.Generic.Dictionary via for statement LINQ to Entities无法识别方法&#39;System.Collections.Generic.Dictionary` - LINQ to Entities does not recognize the method 'System.Collections.Generic.Dictionary` 如何在 Realm-dotnet 中存储 System.Collections.Generic.Dictionary - How to store a System.Collections.Generic.Dictionary in realm-dotnet 枚举System.Collections.Generic.Dictionary中的键<string,string> - enumerate keys in in a System.Collections.Generic.Dictionary<string,string> System.Collections.Generic.Dictionary`Add`vs set&#39;Item` - System.Collections.Generic.Dictionary `Add` vs set `Item` 无法将类型字符串隐式转换为System.Collections.Generic.Dictionary <string,System.Collections.Generic.Dictionary><string,object> &gt; - Cannot implicitly convert type string to System.Collections.Generic.Dictionary<string,System.Collections.Generic.Dictionary><string,object>>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM