首页 > Windows开发 > 详细

xml 换行符处理 c#

时间:2021-07-23 11:13:51      阅读:18      评论:0      收藏:0      [点我收藏+]

XElement.ToString() 默认会把\r\n, \n转化成默认换行符(有的环境是\n,也有的环境是\r\n),若不想自动转化可以采用 NewLineHandling.None:

技术分享图片
 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 }
Write with NewLineHandling.None

测试代码:

转义字符:

\r: 

\n: 


&: &

<: &lt;

>: &gt;

 1 public static void TestXml()
 2 {
 3     var str = "<Root><Element>Value1a&#xA;Value1b&#xD;&#xA;Value1c</Element></Root>";
 4     
 5      var xDoc = XDocument.Parse(str);
 6     var element = xDoc.Descendants("Element").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: {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     using (var sw = new StringWriter())
21     {
22         using (var xw = XmlWriter.Create(sw, settings))
23         {
24             element.WriteTo(xw);                    
25         }
26         
27         var eleStr = sw.ToString();
28         Console.WriteLine("4. Serialize with NewLineHandling.None: {0}", eleStr.Replace("\r", "\\r").Replace("\n", "\\n"));
29     }    
30 }

 

在windows 10 上测试:

1. Element plain value: Value1a
Value1b
Value1c

Below log will show \r \n as visible characters.

2. Element Value: Value1a\nValue1b\r\nValue1c
3. Element.ToString(): <Element>Value1a\r\nValue1b\r\nValue1c</Element>
4. Serialize with NewLineHandling.None: <Element>Value1a\nValue1b\r\nValue1c</Element>

xml 换行符处理 c#

原文:https://www.cnblogs.com/fancy-xt/p/15047022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!