我在我想将其张贴到一个API,包含换行符(\ n)的但不是回车(无\ R)之前,生成XML的情况。
在C#中,虽然,它似乎的XDocument自动添加在其串方法回车:
var inputXmlString = "<root>Some text without carriage return\nthis is the new line</root>";
// inputXmlString: <root>Some text without carriage return\nthis is the new line</root>
var doc = XDocument.Parse(inputXmlString);
var xmlString = doc.Root.ToString();
// xmlString: <root>Some text without carriage return\n\rthis is the new line</root>
在doc.Root.ToString()中,针对压痕不为XML消息的接收器解释作为一个整体关系的元件之间加入集\ n \ r的。但是,ToString()方法也增加了实际的文本字段,我需要(后\ n不\ r)的保持独立的换行符内\ r。
我知道我可以做最后的字符串替换,去除之前的实际HTTP后,最后一个字符串的所有回车执行,但是这似乎只是错误的。
构建使用的XElement对象而不是Document.Parse的XML文档时的问题是一样的。这个问题也仍然存在,即使我用一个CDATA元素来包装文本。
任何人都可以向我解释,如果我做错了什么或有什么实现我尝试做一些干净的方式?
XNode.ToString
是底层使用的XmlWriter
了方便 - 您可以看到在reference source代码。
每the documentation为XmlWriterSettings.NewLineHandling
:
替换设置告诉的XmlWriter以取代\ r \ n,这是由微软Windows操作系统使用的新行格式的新行字符。这有助于确保该文件可通过记事本或Microsoft Word应用程序正确显示。此设置也将替换在用字符实体属性的新行保存字符。这是默认值。
所以这就是为什么你看到这个当您转换您的元素回字符串。如果你想改变这种行为,你必须用自己的XmlWriter
创建自己的XmlWriterSettings
:
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineHandling = NewLineHandling.None
};
string xmlString;
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw, settings))
{
doc.Root.WriteTo(xw);
}
xmlString = sw.ToString();
}
你有没有尝试过:
how to remove carriage returns, newlines, spaces from a string
string result = XElement.Parse(input).ToString(SaveOptions.DisableFormatting);
Console.WriteLine(result);
其他答案并没有为我工作(后我把它转换成VB)
但这并:
返回xDoc.ToString(SaveOptions.DisableFormatting)