2017-08-30 102 views
0

有沒有寫入OpenXmlPartReader正在讀取的同一OpenXmlPart的方法?我要去檢測讀者的東西,並可能用OpenXmlWriter來寫東西。這裏是行不通的樣本:寫入正在讀取的同一個OpenXmlPart

var ms = new MemoryStream(); 
var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document); 

MainDocumentPart part = doc.AddMainDocumentPart(); 
part.Document = new Document(new Body(new Paragraph(), new Paragraph())); 
doc.Save(); 

var stream = part.GetStream(); 
var reader = OpenXmlReader.Create(stream); 
var writer = OpenXmlWriter.Create(stream); 

reader.Read(); // read w:document 
reader.ReadFirstChild(); // read w:body 
reader.ReadFirstChild(); // read 1st w:p 
writer.WriteElement(new Table()); // try to insert w:tbl 

doc.Save(); // observe only the 2 paragraphs in the `w:body`. 

它看起來像蓋下的Open XML SDK使用幕後XmlReaderXmlWriter,所以也許有一種方法來同步這些?

回答

1

因此,看起來沒有辦法同步開箱即用的OpenXmlReaderOpenXmlWriter

我最終做的是克隆原始文檔,清除零件並有條件地寫入它們,同時讀出OpenXmlReader

這裏是什麼,我做了一個簡單的模型:

var ms = new MemoryStream(); 
var inputDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document); 

MainDocumentPart inputMainPart = inputDoc.AddMainDocumentPart(); 
inputMainPart.Document = new Document(new Body(new Paragraph(), new Paragraph())); 
input.Save(); 

var outputDoc = input.Clone(); 
outputDoc.RemovePart(outputDoc.MainDocumentPart); 
var outputMainPart = outputDoc.AddMainDocumentPart(); 


var reader = OpenXmlReader.Create(inputMainPart); 
var writer = OpenXmlWriter.Create(outputMainPart); 
// write body/document 

reader.Read(); // read w:document 
reader.ReadFirstChild(); // read w:body 
reader.ReadFirstChild(); // read 1st w:p 

do { 
    writer.WriteElement(new Table()); // insert w:tbl 
    writer.WriteElement(reader.LoadCurrentElement()); 
} while(reader.ReadNextSibling()); 
doc.Save(); // observe only the 2 paragraphs in the `w:body`.