xmlreader newline \n instead of \r\n

后端 未结 5 1635
不思量自难忘°
不思量自难忘° 2021-01-11 11:32

When I use XmlReader.ReadOuterXml(), elements are separated by \\n instead of \\r\\n. So, for example, if I have XmlDocument representatino of


<         


        
5条回答
  •  失恋的感觉
    2021-01-11 11:34

    Solution 1: Write entitized XML

    Use a well configured XmlWriter with NewLineHandling.Entitize option so the XmlReader will not eliminate normalize the line endings.

    You can use such a custom XmlWriter even with XDocument:

    xDoc.Save(XmlWriter.Create(fileName, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize }));
    

    Solution 2: Read non-entitized XML without normalization

    Solution 1 is the cleaner way; however, it is possible that you already have the non-entitized XML and you cannot modify the creation and still you want to prevent normalization. The accepted answer suggests a replace but that replaces every \n occurrences blindly even if it is not desirable. To retrieve all of the line endings as they are in the file you can try to use the legacy XmlTextReader class, which does not normalize XML files by default. You can use it with XDocument, too:

    var xDoc = XDocument.Load(new XmlTextReader(fileName));
    

提交回复
热议问题