这段代码接受我生成的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>
<list>
<li>A point</li>
<li>another point</li></list>
</paragraph>
<header>
<author>Mads</author>
<date>01-01-0001</date>
<subject>Ny HIF Aftale</subject>
</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上时,会发生奇怪的转换。
如何修复此嵌套代码问题..?