OpenXml Word 脚注

ami*_*ros 1 c# ms-word docx openxml openxml-sdk

我正在尝试遍历 Word 文档并从中提取脚注,并参考它们在段落中的位置。
我不知道该怎么做。

我看到为了获得所有脚注,我可以这样做:

FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();

    foreach (var footnote in footnotes)
    {
         ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何知道每个脚注在段落中的位置。
例如,我想添加一个脚注,并将它放在之前作为脚注的文本内的括号中。
我该怎么做呢?

小智 5

您必须找到FootnoteReference与 .id 相同的元素FootNote。这将为您提供Run脚注所在的元素。

示例代码:

FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    var footnotes = footnotesPart.Footnotes.Elements<Footnote>();
    var references = doc.MainDocumentPart.Document.Body.Descendants<FootnoteReference>().ToArray();
    foreach (var footnote in footnotes)
    {
        long id = footnote.Id;
        var reference = references.Where(fr => (long)fr.Id == id).FirstOrDefault();
        if (reference != null)
        {
            Run run = reference.Parent as Run;
            reference.Remove();
            var fnText = string.Join("", footnote.Descendants<Run>().SelectMany(r => r.Elements<Text>()).Select(t => t.Text)).Trim();
            run.Parent.InsertAfter(new Run(new Text("(" + fnText + ")")), run);
        }
    }
}
doc.MainDocumentPart.Document.Save();
doc.Close();
Run Code Online (Sandbox Code Playgroud)