.net - 如何使用 OpenXML 修改 word 超链接

标签 .net url hyperlink ms-word openxml

如何使用 OpenXml 和 .Net 将 Microsoft Word 网址中的超链接从“http://www.google.com”修改为“MyDoc.docx”?

我可以获取文档中的所有超链接,但找不到要更改的 url 属性。我有这样的事情:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"C:\Users\Costa\Desktop\AAA.docx", true))
{
    MainDocumentPart mainPart = wordDoc.MainDocumentPart;
    Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
}

谢谢

最佳答案

很遗憾,您无法使用 OpenXml 直接更改超链接路径。唯一的方法是找到当前超链接的 HyperlinkRelation 对象并将其替换为具有相同关系 Id 但新超链接路径的 hew 对象:

using DocumentFormat.OpenXml.Wordprocessing;

MainDocumentPart mainPart = doc.MainDocumentPart;
                Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
                if (hLink != null)
                {
                    // get hyperlink's relation Id (where path stores)
                    string relationId = hLink.Id;
                    if (relationId != string.Empty)
                    {
                        // get current relation
                        HyperlinkRelationship hr = mainPart.HyperlinkRelationships.Where(a => a.Id == relationId).FirstOrDefault();
                        if (hr != null)
                        // remove current relation
                        { mainPart.DeleteReferenceRelationship(hr); }
                        //add new relation with same Id , but new path
                        mainPart.AddHyperlinkRelationship(new System.Uri(@"D:\work\DOCS\new\My.docx", System.UriKind.Absolute), true, relationId);
                    }
                }
                // apply changes
                doc.Close();

关于.net - 如何使用 OpenXML 修改 word 超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082387/

相关文章:

c# - Windows 服务 在安装时选择用户或系统帐户

c# - C# 中的接口(interface)和后期绑定(bind)

java - 谷歌搜索并用java打印结果

javascript - PHP stringID 未从 echo 中读取 onclick

javascript - 处理操作调用 URL 后 HTML 更改 URL

hyperlink - 如何在没有宏/vba 的情况下创建从 Word 到 Excel 特定单元格的超链接?

javascript - "Focus"动态链接事件

c# - 从二进制文件中的结构中解析内容

c# - 从 Internet 下载 HTML 后,字符串中的字符发生了变化

javascript - jQuery:获取链接的 html 代码