我有一种情况,我想在将XML发布到API之前生成xml,其中包含换行符(\ n)但不包含回车符(no \ 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>
Run Code Online (Sandbox Code Playgroud)
在doc.Root.ToString()中,在缩进元素之间添加了\ n \ r的集合,这对于接收者对xml消息的整体解释并不重要。但是,ToString()方法还在实际文本字段中添加了\ r,我需要在其中保留独立的换行符(在\ n之后没有\ r)。
我知道我可以做最后一个字符串替换,从要执行的实际HTTP发布之前删除最后一个字符串中的所有回车符,但这似乎是错误的。
使用XElement对象而不是Document.Parse构造xml文档时,问题是相同的。即使我使用CData元素包装文本,问题也仍然存在。
任何人都可以向我解释,如果我做错了什么,或者有某种干净的方法来实现自己的目标?