使用XDocument来编写原始XML

我试图用XML Spreadsheet 2003格式创build电子表格(所以Excel可以读取它)。 我正在使用XDocument类写出文档,并且需要在<Cell>标签之一的主体中获取换行符。 Excel读取和写入时,要求文件具有文字string embeddedstring中以正确显示电子表格中的换行符。 它也是这样写的。

问题是,当我在数据中有换行符时,XDocument正在编写CR-LF(\ r \ n),并且当我尝试在inputstring上执行.Replace()时,它自动转义为&符号,用&amp;#10; 在我的文件中,哪个Excel只是愉快地写出一个string文字。

有没有办法让XDocument写出文字 作为XMLstream的一部分? 我知道我可以通过从XmlTextWriter派生,或者直接用TextWriter写出文件,但是如果可能的话,我宁愿不要。

我想知道是否可以直接使用XmlWriterWriteRaw

快速检查表明, XmlDocument使它稍微好一点,但XML和空白变得非常棘手非常迅速…

我与这个问题奋斗了几天,终于想出了这个解决scheme。 我使用XMLDocument.Save(Stream)方法,然后从stream中获取格式化的XMLstring。 然后,我取代了&amp;#10; 出现与&#10; 并使用TextWriter将string写入文件。

 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;'s 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();