C# 使用嵌套的XML标记获取错误的输出
这段代码获取我生成的XDocument并将其保存为XML文件:C# 使用嵌套的XML标记获取错误的输出,c#,xml,linq-to-xml,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");
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);
};
}
static void Main(字符串[]args)
{
Dictionary dic=新字典();
dic.添加(“标题”、“纽约州后”);
dic.添加(“第0段”,“此处有一些文本”);
dic.添加(“第1段”,“此处新行有更多文本”);
添加(“第2段”,“一点”\n另一点” ”;
添加(“标头”、“Mads\n”+新日期时间().ToSortDateString()+“\nY HIF Aftale”);
XDocument xd=WordFileGenerator.Parse(dic);
string path=“C:\\Users\\Vipar\\Desktop”;
使用(var writer=new XmlTextWriter(path+“\\test.xml”,新的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>
纽约Aftale酒店
这里有一些文字
这里的新行上还有一些文字
列表
liA点/li
LIANOTHE point/li/list
作者/作者
日期01-01-0001/日期
主题日期/主题日期后的HIF
我用于生成此文件的代码如下所示:
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解析(字典dic)
{
XDocument newXDoc=新XDocument();
newXDoc.Add(新元素(“文档”),
新XElement(“标题”,dic[“标题]),
其中((kvp)=>kvp.Key.ToLower().StartsWith(“段落”))
.Select(kvp=>new-XElement(kvp.Key.Substring(0,9),kvp.Value)),
新元素(“标题”,dic[“标题”])
)
);
返回newXDoc;
}
当我将信息放在XDocument上时,会发生奇怪的转换
如何解决这个嵌套标记问题?
只是一个字符串,而不是linq2xml将转义到列表的嵌套标记。我认为@xeondev也是这样。但它仍然可以。我看不出有什么奇怪的地方,字符串是这样工作的,如果你不想嵌套标签,我会选择字典
,为标题添加一个XElement。我同意xeondev,你要么需要将XElement
值放入字典,要么需要使用XElement.parse(kvp.Value)解析值
。但是,只有当内容是格式良好的XML元素标记时,这才有效。对于paragraph0
和paragraph1
值,如果不能使用这种方法,则需要将所有内容包装到标记中。