【发布时间】:2016-09-29 15:25:42
【问题描述】:
我有一个案例,我想在将其发布到 API 之前生成 xml,包含换行符 (\n) 但不包含回车符(无 \r)。
不过,在 C# 中,XDocument 似乎会在其 to-string 方法中自动添加回车:
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() 中,在元素之间添加了一组 \n\r 用于缩进,这对于接收者对整个 xml 消息的解释无关紧要。但是,ToString() 方法还在我需要保留独立换行符的实际文本字段中添加了 \r(后面没有 \r 的 \n)。
我知道我可以进行最终字符串替换,在实际执行 HTTP 发布之前从最终字符串中删除所有回车,但这似乎是错误的。
使用 XElement 对象而不是 Document.Parse 构造 xml 文档时,问题是相同的。即使我使用 CData 元素来包装文本,问题也仍然存在。
如果我做错了什么,或者是否有一些干净的方法可以实现我尝试做的事情,谁能向我解释一下?
【问题讨论】:
标签: c# xml linq-to-xml