C# 如何防止 xml 将 /r/n 转换为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18693646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:56:45  来源:igfitidea点击:

How to keep xml from converting /r/n into 


c#xmlms-word

提问by Alnedru

I have here a small code:

我这里有一个小代码:

string attributeValue = "Hello" + Environment.NewLine + " Hello 2";

XElement element = new XElement("test");
XElement subElement = new XElement("subTest");
XAttribute attribute = new XAttribute("key", "Hello");
XAttribute attribute2 = new XAttribute("key2", attributeValue);
subElement.Add(attribute);
subElement.Add(attribute2);
element.Add(subElement);

Console.Write(element.ToString());
Console.ReadLine();

I have an issue, basically the /r/n or the new line is converted in 
in attribute, but I dont want to have it, I want to keep it /r/n as when I use this XML with the Microsoft Word documents template, the new lines are not implemented, although it is multilined text, in word document I only get the spaces. But no new lines :/

我有一个问题,基本上 /r/n 或新行在
属性中转换,但我不想拥有它,我想保留它 /r/n,就像我将此 XML 与 Microsoft Word 文档模板一起使用时一样,新行没有实现,虽然它是多行文本,但在word文档中我只得到空格。但没有新行:/

Anyone has any idea?

任何人有任何想法?

Although i've set the allow multi line int he property of the field in the template.

尽管我已经在模板中设置了该字段的允许多行属性。

采纳答案by varocarbas

Actually the behaviour you get with 
is the same than the one of Environment.NewLine. You can do a simple test to confirm this (add two TextBoxesto your Formwith the Multiline propertyset to True: textBox1and textBox2):

其实你用得到的行为
比的一个相同Environment.NewLine。你可以做一个简单的测试来确认这一点(TextBoxes在你FormMultiline property设置中添加两个TruetextBox1textBox2):

textBox1.Text = element.ToString(); //

string text = element.ToString().Replace("
", Environment.NewLine);
textBox2.Text = text; ///r/n

On the other hand, if you want to avoid the 
part anyway (for example: because of wanting to output the given string to an external program not working on .NET), you can just rely on the aforementioned Replaceafter dealing with XElementand new lines.

另一方面,如果您
无论如何都想避免该部分(例如:因为想要将给定的字符串输出到不在 .NET 上运行的外部程序),您可以Replace在处理XElement和换行后依赖上述内容。