How to modify word hyperlink with OpenXML

.net, hyperlink, ms-word, openxml, url

Solution

Unfortunately u could not directly change hyperlink path using OpenXml. The only way is to find HyperlinkRelation object for current hyperlink and replace it with hew object with same relation Id, but new hyperlink path:

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();

Problem

How can i modify the hypelink in Microsoft Word url from "http://www.google.com" to "MyDoc.docx" using OpenXml and .Net ? I can obtain all hyperlinks in the document but can't find the url properties to change. I have something like this: ``` using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"C:\Users\Costa\Desktop\AAA.docx", true)) { MainDocumentPart mainPart = wordDoc.MainDocumentPart; Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault(); } ``` Thanks

Original source