Replacing in inner Text in open xml element?

shishi picture shishi · Jul 29, 2011 · Viewed 12.1k times · Source

I'm using open xml SDK 2.0 and i'm kind off new to this.

I have actually created a quickpart (containg content control) in my word 2007 document named "hello.docx". Now I need to copy the quickpart into the other location of the same document named "hello.docx". I was very thank full for this post http://www.techques.com/question/1-3448297/Replacing-Content-Controls-in-OpenXML and same thing is posted on stack overflow forum for which i was very thank full :)...This post just deletes the content control but keeps the content in Content control.

With the help of the above link I was able to modify the code to clone the content control and append to the same document (This part of my code is working). But i have problem in innerText. Though i replace the innerText in the open Xml element, it is not geting reflected in the doucument.

public static void AddingSdtBlock(string filename, string sdtBlockTag)
{
    using (WordprocessingDocument doc = WordprocessingDocument.Open(filename,true))
    {
        MainDocumentPart mainDocumentPart = doc.MainDocumentPart;
        List<SdtBlock> sdtList = mainDocumentPart.Document.Descendants<SdtBlock>().ToList();
        SdtBlock sdtA = null;

        foreach (SdtBlock sdt in sdtList)
        {
            if (sdt.SdtProperties.GetFirstChild<Tag>().Val.Value == sdtBlockTag)
            {
                sdtA = sdt;
                break;
            }
        }
        SdtBlock cloneSdkt = (SdtBlock)sdtA.Clone();



        OpenXmlElement sdtc = cloneSdkt.GetFirstChild<SdtContentBlock>();
      //  OpenXmlElement parent = cloneSdkt.Parent;

        OpenXmlElementList elements = cloneSdkt.ChildElements;

       // var mySdtc = new SdtContentBlock(cloneSdkt.OuterXml);

        foreach (OpenXmlElement elem in elements)
        {
          string innerxml=  elem.InnerText ;
          if (innerxml.Length>0)
          {
              string modified = "Class Name : My Class.Description : mydesc.AttributesNameDescriptionMy Attri name.my attri desc.Operations NameDescriptionmy ope name.my ope descriptn.";
             string replace= elem.InnerText.Replace(innerxml, modified);
            // mainDocumentPart.Document.Save();
          }
           // string text = parent.FirstChild.InnerText;
           // parent.Append((OpenXmlElement)elem.Clone());
        }

        mainDocumentPart.Document.Body.AppendChild<SdtBlock>(cloneSdkt);

        //sdtA.Remove();
    }
}

The Replaced string in the openXML element is not geting reflected in the document. Any help would be really appreciated.

Thanks in advance,

Answer

Dave Cauldron picture Dave Cauldron · Jul 23, 2013

Your "string replace= " line does nothing. By creating a variable you seem aware that string.Replace() is not an in-place replacement, but then you are not doing anything with the variable.