2012-12-03 73 views
2

這是不是一個真正的問題,因爲我已經發現了這個問題Retrieving descendants from OpenXml body爲什麼我得到一個OpenXmlUnknownElement?

後代都使用此代碼檢索的原因。

using System.IO; 
using DocumentFormat.OpenXml.Packaging; 
using DocumentFormat.OpenXml.Wordprocessing; 
namespace Testolini 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var filename = Path.GetTempFileName(); 
      var word = WordprocessingDocument.Create(filename, DocumentFormat.OpenXml.WordprocessingDocumentType.Document); 
      word.AddMainDocumentPart(); 
      word.MainDocumentPart.Document = new Document(
               new Body(
                new Paragraph(
                 new Run(
                  new Paragraph(
                   new Run(
                    new Text("test1"))), 
                  new Paragraph(
                   new Run(
                    new Text("test2"))), 
                  new Paragraph(
                   new Run(
                    new Text("test3"))))))); 
      word.Close(); 

      using (var memorystream = new MemoryStream(File.ReadAllBytes(filename))) 
      { 
       var word2 = WordprocessingDocument.Open(memorystream, true); 

       var descendants = word2.MainDocumentPart.Document.Body.Descendants(); 

       word.Close(); 

      } 
     } 
    } 
} 

如果您遇到同樣的問題。這可能是因爲XML fil不符合ECMA標準。 在我的情況下,問題是我嵌套了段落。

當我使用bytearray和memorystream打開文檔時出現問題。它看起來像元素進行了驗證,如果驗證失敗,它變成了OpenXmlUnknownElement。

如果任何人有更好的解釋,也許這個問題更準確的原因,我想更多地瞭解它。

+0

我認爲這發生在您更改文檔以使其包含父母下方不應該與該父母關聯的子女時發生。這是您的解決方案中可能的情況嗎? – Maarten

+0

是的。在我的情況下,你不能在運行(/段落)中有段落。我試圖找到一種方法來執行驗證,以便不會發生這種情況。 –

+0

這可能有所幫助:http://msdn.microsoft.com/en-us/library/office/bb497334.aspx – Maarten

回答

2

一個Run不能包含另一個Paragraph

這裏是一個Run有效的子元素的列表:

annotationRef(評論信息塊)
BR(斷裂)
commentReference(評論內容參考點)
contentPart(內容部分)
continuationSeparator(繼續分隔符)
cr(回車)
dayLong(日期塊 - 長日格式)
dayShort(日期座 - 短節格式)
delInstrText(刪除域代碼)
delText(刪除文本)
圖(DrawingML對象)
endnoteRef(尾註引用標記)
endnoteReference(尾註參考)
fldChar(複雜場特徵)
footnoteRef(腳註引用標記)
footnoteReference(腳註參考)
instrText(現場碼)
lastRenderedPageBreak(上一次計算分頁符的位置)
一個月的(日期座 - 長月份格式)
monthShort(日期座 - 短月格式)
noBreakHyphen(非斷連字符)
對象(嵌入對象)
pgNum(頁數塊)
PTAB(絕對位置製表符)
RPR(運行屬性)
紅寶石(拼音指南)
分離器(腳註/尾註分隔標記)
softHyphen(可選連字符)
符號(符號字符)
T(文本)
選項卡(製表符)
爲期一年(日期座 - 龍年格式)
yearShort(日期座 - 短短一年格式)

摘自MSDN

爲什麼你需要「嵌套」段落?

+0

我不。該程序自動生成openxml文件,並在程序中的某個地方段落嵌套導致我的錯誤。 –

相關問題