简体   繁体   中英

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.

The application will generate a Word Document based on the XDocument. 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:

<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:

  1. Take out all the Paragraphs temporarily
  2. Fill in the XDocument with appropriate XElement's

I just don't know how to do this without running into possible NullPointerExceptions or the likes. 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?

A new paragraph is defined as when the previous paragraph reaches a newline character (\\n)

Using LinqToXML, this will put all dictionary keys starting with "paragraph" into your document:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM