.NET OpenXML SDK 2 RunProperties 为 Null

Dan*_*rik 5 .net word-2007 docx openxml openxml-sdk

我正在尝试阅读 Word 2007 docx 文档。

该文档在 Word 中看起来不错,但是当我尝试使用我的代码读取 id 时,所有 Run 对象都将 RunProperites 设置为 null。

我最感兴趣的属性是 RunProperies.FontSize,但不幸的是它也是 null,我可以访问的唯一属性是 InnerText。

我的代码如下所示:

using (WordprocessingDocument doc = WordprocessingDocument.Open(filename, true))
{
    MainDocumentPart mainPart = doc.MainDocumentPart;
    IList<Paragraph> paragraphList = doc.MainDocumentPart.Document.Body.Elements<Paragraph>().ToList<Paragraph>();

    foreach (Paragraph pr in paragraphList)
    {   
        IList<Run> runList = pr.Elements<Run>().ToList<Run>();
        foreach (Run r in runList)
        {
            // Some logic
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经将我的文档最小化到尽可能简单,它看起来像这样http://dl.dropbox.com/u/204110/test.docx

我有类似的文件,可以很好地阅读。OpenXML SDK 2 中是否可能存在错误?

有没有人遇到过类似的问题?任何帮助将不胜感激。谢谢你!

Ada*_*han 4

FontSize不是必需元素,RunProperties也不是必需元素。对于每次运行,请验证r.RunProperties是否不为 null,然后在尝试读取值之前验证r.RunProperties.FontSize是否不为 null。大致如下:

uint fontSize = SOME_DEFAULT_FONT_SIZE;
RunProperties propertiesElement = r.RunProperties;
if (propertiesElement != null) {
  FontSize sizeElement = propertiesElement.FontSize;
    if (sizeElement != null) {
      fontSize = sizeElement.Val.Value;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 SDK 附带的 DocReflector 工具查看提供的 docx 文件,您可以看到前 3 次运行指定了字体大小,但第 4 次运行没有指定字体大小。