使用XDocument编写原始XML

3
我正在尝试创建一个 XML Spreadsheet 2003 格式的电子表格(这样 Excel 可以读取它)。我使用 XDocument 类编写文档,并需要在一个 <Cell> 标签的正文中获取换行符。当 Excel 读取和写入文件时,需要将字面字符串 &#10; 嵌入到字符串中才能正确显示电子表格中的换行符。它也会将其写出。
问题是 XDocument 在我的数据中有换行符时会写入 CR-LF (\r\n),而当我尝试对输入字符串执行 .Replace() 时,它会自动转义并返回“&amp;#10;”,因此我最终得到的文件实际上写出了一个字符串字面量。
有没有办法使 XDocument 将字面值 &#10; 写入 XML 流中?我知道可以通过从 XmlTextWriter 派生,或者直接使用 TextWriter 编写文件来完成,但如果可能的话,我更倾向于避免这样做。
2个回答

3

我在想是否直接使用XmlWriterWriteRaw会更好?

快速检查表明,XmlDocument做得稍微好一些,但是xml和空格很快就变得棘手了...


同意,不过我建议使用XmlWriter.WriteWhitespace()而不是WriteRaw来输出特定的空白字符。 - Dour High Arch
看起来我得走那条路了。 - stames

2

我曾经花了几天时间与这个问题斗争,最终想出了以下的解决方案。我使用了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;'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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接