Using XDocument to write raw XML

I am trying to create a table in XML format Spreadsheet 2003 (so that Excel can read it). I am writing a document using the XDocument class, and I need to get a new line in the body of one of the tags <Cell>. Excel, when it reads and writes, requires the files to have a literal string &#10;embedded in the string in order to correctly show the new row in the spreadsheet. He also writes it down as such.

The problem is that XDocument writes CR-LF (\ r \ n) when I have new lines in my data and it automatically accelerates ampersands for me when I try to do .Replace()in the input line, so I end up with &amp;#10;in my a file that Excel simply happily writes out as a string literal.

Is there a way to get XDocument to write a literal &#10;as part of an XML stream? I know that I can do this by exiting from XmlTextWriter or literally just writing out a file using TextWriter, but I would prefer if not possible.

+3
source share
2 answers

I wonder if it might be better to use XmlWriterdirectly, WriteRawhuh?

A quick check shows that it XmlDocumentdoes a slightly better job, but xml and whitespace get complex very quickly ...

+3
source

, , . XMLDocument.Save(Stream), XML . &amp;#10; &#10; TextWriter .

string xml = "<?xml version=\"1.0\"?><?mso-application progid='Excel.Sheet'?><Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
xml += "<Styles><Style ss:ID=\"s1\"><Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/></Style></Styles>";
xml += "<Worksheet ss:Name=\"Default\"><Table><Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"75\" /><Row><Cell ss:StyleID=\"s1\"><Data ss:Type=\"String\">Hello&amp;&#35;10;&amp;&#35;10;World</Data></Cell></Row></Table></Worksheet></Workbook>";

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml); //load the xml string
System.IO.MemoryStream stream = new System.IO.MemoryStream();
doc.Save(stream); //save the xml as a formatted string
stream.Position = 0; //reset the stream position since it will be at the end from the Save method
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string formattedXML = reader.ReadToEnd(); //fetch the formatted XML into a string
formattedXML = formattedXML.Replace("&amp;#10;", "&#10;"); //Replace the unhelpful &amp;#10; with the wanted endline entity
System.IO.TextWriter writer = new System.IO.StreamWriter("C:\\Temp\test1.xls");
writer.Write(formattedXML); //write the XML to a file
writer.Close();
+2

Source: https://habr.com/ru/post/1729328/


All Articles