簡體   English   中英

使用XDocument編寫原始XML

[英]Using XDocument to write raw XML

我正在嘗試以XML Spreadsheet 2003格式創建電子表格(因此Excel可以閱讀它)。 我正在使用XDocument類編寫文檔,我需要在其中一個<Cell>標記的主體中獲取換行符。 Excel在讀寫時要求文件具有文字字符串&#10; 嵌入在字符串中以正確顯示電子表格中的換行符。 它也是這樣寫的。

問題是當我在我的數據中有換行符時,XDocument正在編寫CR-LF(\\ r \\ n),當我嘗試在輸入字符串上執行.Replace()時,它會自動為我轉義&符號,所以我最終與&amp;#10; 在我的文件中,Excel只是樂意寫出一個字符串文字。

有沒有辦法讓XDocument寫出文字&#10; 作為XML流的一部分? 我知道我可以通過派生自XmlTextWriter來實現,或者只是用TextWriter寫出文件,但是如果可能的話我不想這樣做。

我想知道直接使用XmlWriterWriteRaw是否更好?

快速檢查表明XmlDocument稍微好了一點,但是xml和whitespace很快就變得棘手......

我和這個問題斗爭了幾天,最后提出了這個解決方案。 我使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM