使用嵌套的XML标记获取错误的输出

时间:2013-05-08 10:09:25

标签: c# xml linq-to-xml

这段代码接受我生成的XDocument并将其保存为XML文件:

    static void Main(string[] args)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("title", "Ny Aftale");
        dic.Add("paragraph0", "Some text here");
        dic.Add("paragraph1", "Some more text on a new line here");
        dic.Add("paragraph2", "<list>\t\n<li>A point</li>\n<li>another point</li></list>");
        dic.Add("header", "<author>Mads</author>\n<date>" + new DateTime().ToShortDateString() + "</date>\n<subject>Ny HIF Aftale</subject>");
        XDocument xd = WordFileGenerator.Parse(dic);
        string path = "C:\\Users\\Vipar\\Desktop";
        using (var writer = new XmlTextWriter(path + "\\test.xml", new UTF8Encoding(false)))
        {
            xd.Save(writer);
        };
    }

问题是,这个字典中的嵌套标签(因为我将字典变成XML文档,不要问)被制成它们的另一种表示形式,而不是它们应该是什么。鉴于上面的字典,我得到的是输出:

<document>
<title>Ny Aftale</title>
<paragraph>Some text here</paragraph>
<paragraph>Some more text on a new line here</paragraph>
<paragraph>
  &lt;list&gt;  
  &lt;li&gt;A point&lt;/li&gt;
  &lt;li&gt;another point&lt;/li&gt;&lt;/list&gt;
</paragraph>
  <header>
  &lt;author&gt;Mads&lt;/author&gt;
  &lt;date&gt;01-01-0001&lt;/date&gt;
  &lt;subject&gt;Ny HIF Aftale&lt;/subject&gt;
  </header>
</document>

我用来生成它的代码如下所示:

    public static XDocument Parse(Dictionary<String, String> dic)
    {
        XDocument newXDoc = new XDocument();
        newXDoc.Add(new XElement("document",
            new XElement("title", dic["title"]),
            dic.Where((kvp) => kvp.Key.ToLower().StartsWith("paragraph"))
                .Select(kvp => new XElement(kvp.Key.Substring(0,9), kvp.Value)),
            new XElement("header", dic["header"])
        )
    );

        return newXDoc;
    }

当我将信息放在XDocument上时,会发生奇怪的转换。

如何修复此嵌套代码问题..?

0 个答案:

没有答案
相关问题