Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xmlreader newline \n instead of \r\n

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

<A>
<B>
</B>
</A>

I get

<A>\n<B>\n</B>\n</A>

Is there an option to specify newline character? XmlWriterSettings has it but XmlReader doesn't seem to have this.

Here is my code to read xml. Note that XmlWriterSettings by default has NewLineHandling = Replace

XmlDocument xmlDocument = <Generate some XmlDocument>
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

// Use a memory stream because it accepts UTF8 characters.  If we use a 
// string builder the XML will be UTF16.
using (MemoryStream memStream = new MemoryStream())
{
    using (XmlWriter xmlWriter = XmlWriter.Create(memStream, settings))
    {
        xmlDocument.Save(xmlWriter);
    }

    //Set the pointer back to the beginning of the stream to be read
    memStream.Position = 0;
    using (XmlReader reader = XmlReader.Create(memStream))
    {
        reader.Read();
        string header = reader.Value;
        reader.MoveToContent();
        return "<?xml " + header + " ?>" + Environment.NewLine + reader.ReadOuterXml();
    }
}
like image 427
user156144 Avatar asked Nov 25 '09 00:11

user156144


2 Answers

XmlReader will automatically normalize \r\n\ to \n. Although this seems unusual on Windows, it is actually required by the XML Specification (http://www.w3.org/TR/2008/REC-xml-20081126/#sec-line-ends).

You can do a String.Replace:

string s = reader.ReadOuterXml().Replace("\n", "\r\n");
like image 56
Jason Kresowaty Avatar answered Sep 19 '22 12:09

Jason Kresowaty


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);
}
like image 33
CMarsden Avatar answered Sep 16 '22 12:09

CMarsden