Click here to Skip to main content
15,924,196 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to add a comment in a docx file programmatically through C# based on the condition if the text encountered is enclosed in square bracketts but it caters only first encounter of the square brackets case. It throws an exception when it encounters the second instance of square brackett. The exception says OpenXMLPackage Exception was unhandled "Only one instance of the type is allowed for this parent."
Please find the code below and help me in resolving it.Thanks in advance

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Packaging;
using System.Xml;
using DocumentFormat.OpenXml.Drawing;
namespace CommentsOOXML
{
    public partial class Comments : Form
    {
        XmlNamespaceManager nsManager = null;
        public Comments()
        {
            InitializeComponent();
        }
        private void Comments_Load(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"c:\test3.docx", true);
 
       
            MainDocumentPart docPart = wordDoc.MainDocumentPart;
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(docPart.GetStream());
            //add comment related elements to the main document
            XmlElement commentStartnode = xdoc.CreateElement("w:commentRangeStart", wordmlNamespace);
            //XmlElement 
            XmlAttribute attr = commentStartnode.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
            attr.Value = "0";
            XmlNode commentNode = null;
            NameTable nt = new NameTable();
            nsManager = new XmlNamespaceManager(nt);
            nsManager.AddNamespace("w", wordmlNamespace);
            string charremove="[ ]";
            int i = 0;
            XmlNodeList comm = xdoc.SelectNodes("//w:r", nsManager);
          //  WordprocessingCommentsPart commentpart = docPart.AddNewPart<WordprocessingCommentsPart>();
            
            foreach (XmlNode nod in comm)
            {
                string commentNote = nod.InnerText.ToString().Trim();
                //commentpart = docPart.AddNewPart<WordprocessingCommentsPart>();
                // if (commentNote.StartsWith("[") && commentNote.EndsWith("]"))
                if (commentNote.Contains("["))
                {
                    commentNode = nod;
                                 
                    XmlNode node1 = commentNode.ParentNode;
                    node1.InsertBefore(commentStartnode, commentNode);
                    XmlElement commentEndnode = xdoc.CreateElement("w:commentRangeEnd", wordmlNamespace);
                    XmlAttribute attr1 = commentEndnode.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
                    attr1.Value = "0";
                   // attr1.Value = "i";
                    node1.InsertAfter(commentEndnode, commentNode);
                    // create comment reference with new w:r
                    XmlElement commentRefnode = xdoc.CreateElement("w:r", wordmlNamespace);
                    XmlNode node2 = commentNode.ParentNode;
                    node2.AppendChild(commentRefnode);
                    XmlElement commentRefnode1 = xdoc.CreateElement("w:commentReference", wordmlNamespace);
                    XmlAttribute attr2 = commentRefnode1.Attributes.Append(xdoc.CreateAttribute("w:id", wordmlNamespace));
                    attr2.Value = "0";
                    //attr2.Value = "i";
                    commentRefnode.AppendChild(commentRefnode1);

                    //MessageBox.Show(xdoc.InnerXml.ToString());
                    xdoc.Save(docPart.GetStream(FileMode.Create, FileAccess.Write));
                    XmlDocument commt = new XmlDocument();
                    //get the comment part from the main part
                    WordprocessingCommentsPart commentpart = docPart.AddNewPart<WordprocessingCommentsPart>();  
                    //use this method to cmodify the comments.xml file
                    commt.Load(@"..\..\comments.xml");

                    XmlNode comment = commt.SelectSingleNode("//w:r", nsManager);
                    XmlElement cmtText = commt.CreateElement("w:t", wordmlNamespace);
                    
                    comment.AppendChild(cmtText);

                    XmlNode node10 = comm.Item(i);
                    XmlNode commentText = commt.CreateNode(XmlNodeType.Text, "w:t", wordmlNamespace);
                                      commentText.Value = node10.InnerText.Trim(charremove.ToCharArray());

                    cmtText.AppendChild(commentText);
                    StreamWriter commentpartWrt = new StreamWriter(commentpart.GetStream(FileMode.Create, FileAccess.Write));
                    commt.Save(commentpartWrt);
                }
                i++;
            }
            
            wordDoc.Close();
            MessageBox.Show("done");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900