写入正在读取的相同OpenXmlPart

时间:2017-08-30 18:01:31

标签: c# openxml openxml-sdk xmlreader xmlwriter

有没有办法写入OpenXmlPart正在阅读的同一OpenXmlPartReader?我将与读者一起检测事物并可能使用OpenXmlWriter来编写内容。这是一个不起作用的示例:

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 个答案:

答案 0 :(得分: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`.