4

这不是一个真正的问题,因为我已经找到了这个问题的原因从 OpenXml 正文中检索后代

使用此代码检索后代。

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 文件未通过 ECMA 标准进行验证。就我而言,问题是我有嵌套的段落。

当我使用 bytearray 和 memorystream 打开文档时,问题就出现了。看起来元素已经过验证,如果验证失败,它就会变成 OpenXmlUnknownElement。

如果有人对这个问题有更好的解释,也许还有更准确的原因,我很想了解更多。

4

2 回答 2

5

ARun不能包含另一个Paragraph

以下是 a 的有效子元素列表Run

annotationRef(评论信息块)
br(中断)
commentReference(评论内容参考标记)
contentPart(内容部分)
continuationSeparator(继续分隔符标记)
cr(回车)
dayLong(日期块-长日格式)
dayShort(日期块-短日格式) )
delInstrText(已删除字段代码)
delText(已删除文本)
绘图(DrawingML 对象)
endnoteRef(尾注参考标记)
endnoteReference(尾注参考)
fldChar(复杂字段字符)
footnoteRef(脚注参考标记)
footnoteReference(脚注参考)
instrText(字段代码)
lastRenderedPageBreak(上次计算的分页符的位置)
monthLong(日期块 - 长月格式)
monthShort(日期块 - 短月格式)
noBreakHyphen(非中断连字符)
object(嵌入对象)
pgNum(页码块)
ptab(绝对位置选项卡)字符)
rPr(运行属性)
ruby​​(拼音指南)
separator(脚注/尾注分隔符)
softHyphen(可选连字符)
sym(符号字符)
t(文本)
tab(制表符)
yearLong(日期块 - 长年格式)
yearShort (日期块 - 短年格式)

取自MSDN

为什么需要“嵌套”段落?

于 2012-12-05T14:54:21.640 回答
3

文件似乎处于无效状态。我认为当您更改文档以使其包含不应该以这种方式相关的父母之下的孩子时,会发生这种情况。

这可能会有所帮助:http: //msdn.microsoft.com/en-us/library/office/bb497334.aspx

于 2012-12-03T13:55:43.123 回答