【问题标题】:OpenXml Word FootnotesOpenXml Word 脚注
【发布时间】:2016-10-31 13:52:27
【问题描述】:
我正在尝试遍历 Word 文档并从中提取脚注,并引用它们在段落中的位置。
我不知道该怎么做。
我看到为了获得所有脚注,我可以这样做:
FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();
foreach (var footnote in footnotes)
{
...
}
}
但是,我不知道如何知道每个脚注在段落中的位置。
例如,我想添加一个脚注,并将其放在文本中之前作为脚注的位置的括号中。
我该怎么做?
【问题讨论】:
标签:
c#
ms-word
openxml
docx
openxml-sdk
【解决方案1】:
您必须找到与FootNote 具有相同ID 的FootnoteReference 元素。这将为您提供脚注所在的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();