XElement.ToString() 默认会把\r\n, \n转化成默认换行符(有的环境是\n,也有的环境是\r\n),若不想自动转化可以采用 NewLineHandling.None:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 string xmlString; 2 3 var settings = new XmlWriterSettings 4 { 5 OmitXmlDeclaration = true, 6 NewLineHandling = NewLineHandling.None 7 }; 8 9 using (var sw = new StringWriter()) 10 { 11 using (var xw = XmlWriter.Create(sw, settings)) 12 { 13 node.WriteTo(xw); 14 } 15 16 xmlString = sw.ToString(); 17 }
测试代码:
转义字符:
\r: 
\n: 

&: &
<: <
>: >
1 public static void TestXml() 2 { 3 var str = "<Root><string>Value1a
Value1b
Value1c</string></Root>"; 4 5 var xDoc = XDocument.Parse(str); 6 var element = xDoc.Descendants("string").First(); 7 var value = element.Value; 8 Console.WriteLine("1. Element plain value: {0}", value); 9 Console.WriteLine("\r\nBelow log will show \\r \\n as visible characters.\r\n"); 10 Console.WriteLine("2. Element Value Show new line character: {0}", value.Replace("\r", "\\r").Replace("\n", "\\n")); 11 12 Console.WriteLine("3. Element.ToString(): {0}", element.ToString().Replace("\r", "\\r").Replace("\n", "\\n")); 13 14 var settings = new XmlWriterSettings 15 { 16 OmitXmlDeclaration = true, 17 NewLineHandling = NewLineHandling.None 18 }; 19 20 string xmlStr; 21 using (var sw = new StringWriter()) 22 { 23 using (var xw = XmlWriter.Create(sw, settings)) 24 { 25 element.WriteTo(xw); 26 } 27 28 xmlStr = sw.ToString(); 29 Console.WriteLine("4. Serialize with NewLineHandling.None: {0}", xmlStr.Replace("\r", "\\r").Replace("\n", "\\n")); 30 } 31 32 using (var reader = new StringReader(xmlStr)) // If only use StringReader, it will convert \r\n to \n 33 { 34 var ser = new XmlSerializer(typeof(string)); 35 value = (string)ser.Deserialize(reader); 36 Console.WriteLine("5. Deserialize with StringReader: {0}", value.Replace("\r", "\\r").Replace("\n", "\\n")); 37 } 38 39 using (var reader = new XmlTextReader(new StringReader(xmlStr))) // If use XmlTextReader it will keep \r and \n 40 { 41 var ser = new XmlSerializer(typeof(string)); 42 value = (string)ser.Deserialize(reader); 43 Console.WriteLine("6. Deserialize with XmlTextReader: {0}", value.Replace("\r", "\\r").Replace("\n", "\\n")); 44 } 45 }
在windows 10 上测试:
1. Element plain value: Value1a
Value1b
Value1c
Below log will show \r \n as visible characters.
2. Element Value Show new line character: Value1a\nValue1b\r\nValue1c
3. Element.ToString(): <string>Value1a\r\nValue1b\r\nValue1c</string>
4. Serialize with NewLineHandling.None: <string>Value1a\nValue1b\r\nValue1c</string>
5. Deserialize with StringReader: Value1a\nValue1b\nValue1c
6. Deserialize with XmlTextReader: Value1a\nValue1b\r\nValue1c