none
Issue to open word doc after an update with open xml code RRS feed

  • Question

  • Hi

    I developped this code :

    string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
          
          WordprocessingDocument wordPackage = WordprocessingDocument.Open("C:\\test3.docx", true);
          MainDocumentPart part = wordPackage.MainDocumentPart;
         
    
          NameTable nt = new NameTable();
          XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
          nsManager.AddNamespace("w", wordmlNamespace);
          
          
          XmlDocument xmlDoc = new XmlDocument(nt);
          xmlDoc.Load(part.GetStream());
    
          XmlNodeList nodeList = xmlDoc.SelectNodes("//w:bookmarkStart", nsManager);
          
          foreach (XmlNode myXMLNode in xmlDoc.SelectNodes("//w:bookmarkStart", nsManager))
          {
            XmlElement myXElement = xmlDoc.CreateElement("w:t", wordmlNamespace);
            XmlNode myNode = xmlDoc.CreateNode(XmlNodeType.Text, "w:t", wordmlNamespace);
            myNode.Value = "hello world";
            myXElement.AppendChild(myNode);
            myXMLNode.AppendChild(myXElement);
            
          }
          
    
          xmlDoc.Save(new StreamWriter(part.GetStream()));


    I think than I can update my bookmarks with this code, but when I want to open with word my doc, I've got an issue.

    The message is simple : no way to open this doc with word application, some problems have been found

    Do you have any idea ?

     

    Thanks

    Thursday, July 7, 2011 12:27 PM

Answers

  • I found my solution.

     

    foreach (XmlNode myXMLNode in xmlDoc.SelectNodes("//w:bookmarkStart", nsManager))
          {
            XmlElement myRun = xmlDoc.CreateElement("w:r", wordmlNamespace);
            
            XmlElement myXElement = xmlDoc.CreateElement("w:t", wordmlNamespace);
            XmlNode myNode = xmlDoc.CreateNode(XmlNodeType.Text, "w:t", wordmlNamespace);
            myNode.Value = "hello world";
            
            myXElement.AppendChild(myNode);
            myRun.AppendChild(myXElement);
            myXMLNode.AppendChild(myRun);
    
            
            
          }

    With this code, it's working well.

     

    ++

    • Marked as answer by Freud_ Thursday, July 7, 2011 2:09 PM
    Thursday, July 7, 2011 2:08 PM