2012-10-26 21 views
3

如何使用OpenXml和.Net將Microsoft Word網址中的超鏈接從「http://www.google.com」修改爲「MyDoc.docx」?如何使用OpenXML修改單詞超鏈接

我可以獲取文檔中的所有超鏈接,但無法找到要更改的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(); 
} 

感謝

回答

6

不幸的是ü可以不使用的OpenXML直接改變超鏈接路徑。唯一的方法是爲當前超鏈接找到HyperlinkRelation對象,並用具有相同關係Id的hew對象替換它,但新的超鏈接路徑:

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

謝謝!這正是我需要的。你幫了我很多! –

+0

所以你可以接受答案:) – Shelest

+0

@Shelest:獲取超鏈接的關係ID爲空值...這是什麼原因? –