2012-09-17 86 views
2

我想以編程方式鎖定所有內容控件,以便用戶無法刪除它們。Openxml - 鎖定所有內容控件

我正在使用下面的代碼,但我的問題是,在撥打elem.SdtProperties.ChildElements.First<WP.Lock>()時,我得到null

有人可以幫我完成下面提到的代碼嗎?

static void MakeContentControlsNonDeletable() 
     { 
      using (P.WordprocessingDocument wordDoc = 
       P.WordprocessingDocument.Open(@"c:\XYZ.docx", true)) 
      { 
       IEnumerable<WP.SdtElement> elements = 
        wordDoc.MainDocumentPart.Document.Descendants<WP.SdtElement>(); 

       foreach (WP.SdtElement elem in elements) 
       { 
        if (elem.SdtProperties != null) 
        { 
         WP.Lock l = elem.SdtProperties.ChildElements.First<WP.Lock>(); 

         if (l == null) 
         { 
          //Please help here 
          //Please help here 
          //Please help here 
          //Please help here 
         } 

         if (l.Val != WP.LockingValues.SdtContentLocked && l.Val != WP.LockingValues.SdtLocked) 
         { 
          Console.WriteLine("Unlock content element..."); 
          l.Val = WP.LockingValues.SdtLocked; 
         } 
        } 
       } 
      } 

回答

1

看來你的代碼是好的。在另一個存在某個對象並且返回null的場景中,我遇到了同樣的問題。我不知道那時openxml sdk有什麼問題,但我可以告訴你我是如何解決這個問題的。

問題的根本在於,在結構深處的某些點,你知道有一個元素應該被解釋爲一個Lock對象,但是sdk只能將它看作OpenXmlElement(不是它的子類Lock對象),所以這就是爲什麼當你做First<WP.Lock>()你期待一個Lock對象,你知道它在那裏,但你只是空。我所做的就是將所有內容都視爲OpenXmlElement,而忘記了強大的打字。

static void MakeContentControlsNonDeletable() 
    { 
     using (P.WordprocessingDocument wordDoc = 
      P.WordprocessingDocument.Open(@"c:\XYZ.docx", true)) 
     { 
      IEnumerable<OpenXmlElement> elements = 
       wordDoc.MainDocumentPart.Document.Descendants<>(child => child.LocalName == "sdt"); 

      foreach (OpenXmlElement elem in elements) 
      { 
       if (elem.ChildElements.Any(child => child.LocalName == "sdtPr")) 
       { 
        OpenXmlElement sdtPr = elem.ChildElements.FirstOrDefault(child => child.LocalName == "sdtPr"); 
        OpenXmlElement l = sdtPr.ChildElements.FirstOrDefault(child => child.LocalName == "lock"); 

        if (l == null) //At this point if you have your lock object this isn't null 
        { 
         //Please help here 
         //Please help here 
         //Please help here 
        } 

        OpenXmlAttribute valAttribute = l.GetAttribute("val", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); 
        if (valAttribute != null) { 
         valAttribute = new OpenXmlAttribute(); 
        } 

        if (valAttribute.Value != "sdtContentLocked" && valAttribute.Value != "sdtLocked") 
        { 
         Console.WriteLine("Unlock content element..."); 
         valAttribute.Value = "sdtLocked"; 
        } 
       } 
      } 
     } 

我知道這是不是它應該是這樣,我知道所有的對象應該是強類型到其各自的OPENXML SDK類,但在這個時候,發生了很多,這就是爲什麼我這樣做。

希望它有幫助