我在更新 Word 文档中的超链接时遇到问题 (Q如何更新 Word 文档中的正文和超链接)并放大Descendants<T>()
打电话不工作。这是我的代码:
using DocumentFormat.OpenXml.Packaging; //from NuGet ClosedXML
using DocumentFormat.OpenXml.Wordprocessing; //from NuGet ClosedXML
WordprocessingDocument doc = WordprocessingDocument.Open(...filename..., true);
MainDocumentPart mainPart = doc.MainDocumentPart;
IEnumerable<Hyperlink> hLinks = mainPart.Document.Body.Descendants<Hyperlink>();
该文档打开正常,因为mainPart
得到一个值。但hLinks
没有元素。如果我在 Word 中打开 Word 文档,则会出现一个超链接并且可以使用。
在立即窗口中我看到以下值:
mainPart.Document.Body
-->
{DocumentFormat.OpenXml.Wordprocessing.Body}
ChildElements: {DocumentFormat.OpenXml.OpenXmlChildElements}
ExtendedAttributes: {DocumentFormat.OpenXml.EmptyEnumerable<DocumentFormat.OpenXml.OpenXmlAttribute>}
FirstChild: {DocumentFormat.OpenXml.OpenXmlUnknownElement}
HasAttributes: false
HasChildren: true
InnerText: "
lots of data, e.g:
...<w:t>100</w:t>...
mainPart.Document.Body.Descendants<Text>().First()
-->
Exception: "Sequence contains no elements"
如果我什至找不到文本部分,我应该如何找到并替换超链接?
如果您确定正在使用 linq 搜索文件中的某些元素,但没有返回任何内容或者出现异常,则通常表明存在命名空间问题。
如果您发布整个文件,我可以更好地帮助您,但请检查您是否可以为命名空间添加别名,如下所示:
using W = DocumentFormat.OpenXml.Wordprocessing;
然后在你的Descendants
打电话给你做这样的事情:
var hLinks = mainPart.Document.Body.Descendants<W.Hyperlink>();
This answer演示了另一个可以尝试的命名空间技巧。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)