xmlreader newline \n instead of \r\n

后端 未结 5 1165
天命终不由人
天命终不由人 2021-01-11 11:21

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:58

    I had to write database data to an xml file and read it back from the xml file, using LINQ to XML. Some fields in a record were themselves xml strings complete with \r characters. These had to remain intact. I spent days trying to find something that would work, but it seems Microsoft was by design converting \r to \n.

    The following solution works for me:

    To write a loaded XDocument to the XML file keeping \r intact, where xDoc is an XDocument and filePath is a string:

    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings 
        { NewLineHandling = NewLineHandling.None, Indent = true };
    using (XmlWriter xmlWriter = XmlWriter.Create(filePath, xmlWriterSettings))
    {
        xDoc.Save(xmlWriter);
        xmlWriter.Flush();
    }
    

    To read an XML file into an XElement keeping \r intact:

    using (XmlTextReader xmlTextReader = new XmlTextReader(filePath) 
       { WhitespaceHandling = WhitespaceHandling.Significant })
    {
         xmlTextReader.MoveToContent();
         xDatabaseElement = XElement.Load(xmlTextReader);
    }
    

提交回复
热议问题