如何替换注释的InnerText

我尝试过以下方法:

comment.InnerText=comment.InnerText.Replace(comment.InnerText,new_text); 

哪个不起作用,因为我们只能读取InnerText属性。 如何有效地更改InnerText值,以便我可以将修改保存到MainDocumentPart.DocumentMainDocumentPart.Document

编辑: DocumentFormat.OpenXml.Wordprocessing.Comment是评论的类。

编辑2:方法:

 public void updateCommentInnerTextNewWorkItem(List<Tuple> list){ //DOCX.CDOC.Comments -> WordProcessingCommentsPart.Comments //DOCX._CIT -> Dictionary foreach (var comm in DOCX.CDOC.Comments) { foreach (var item in list) { foreach (var item_cit in DOCX._CIT) { if (((Comment)comm).InnerText.Contains("") && item.Item3.Contains(item_cit.Value)) { comm.InnerXml = comm.InnerXml.Replace(comm.InnerText, item.Item1 + ""); //comm.InnerText.Replace(comm.InnerText,item.Item1+""); //DOCX.CDOC.Comments.Save(); //DOCX.DOC.MainDocumentPart.Document.Save(); } if (((Comment)comm).InnerText.Contains("<tag class") && item.Item3.Contains(item_cit.Value)) { //comm.InnerText.Replace(comm.InnerText, item.Item1 + ""); comm.InnerXml = comm.InnerXml.Replace(comm.InnerText, item.Item1 + ""); //DOCX.CDOC.Comments.Save(); //DOCX.DOC.MainDocumentPart.Document.Save(); } } } } DOCX.CDOC.Comments.Save(); DOCX.DOC.MainDocumentPart.Document.Save(); } 

它不是那么容易(但仍然不复杂)。 注释具有结构和文档的正文 – 它可以包含段落,运行等.InititeText将只返回此注释中所有段落的所有运行的文本值,所以现在您了解为什么不能只设置此值。

首先,您必须删除所有评论的段落:

 comment.RemoveAllChildren(); 

下一步是使用包含所需文本的run添加新段落:

 Paragraph paragraph = new Paragraph(); Run run = new Run(); Text text = new Text(); text.Text = "My comment"; run.Append(text); paragraph.Append(run); comment.Append(paragraph); 

毕竟不要忘记保存更改:

 doc.MainDocumentPart.WordprocessingCommentsPart.Comments.Save(); 

它是只读的,因为它返回了删除了所有XML标记的XML内容。 因此设置它将剥离所有XML标记。

如果要替换的文本不跨越标记,则只需替换XML中的文本:

 comment.InnerXml=comment.InnerXml.Replace(comment.InnerText,new_text); 

啊……这有点复杂。我遇到过同样的问题。

您将需要XmlElement类。例如,有一个名为xmlDoc的变量已从XmlDocument实例化。 然后你应该使用SelectSingleNode方法来获取你想要编辑的XmlNode的引用。你需要使用它来将XmlNode转换为XmlElement(假设XmlNode被命名为’node’):

 XmlElement XmlEle = (XmlElement)node; 

同样简单,您可以使用:

 XmlElement XmlEle = (XmlElement)xmlDoc.SelectSingleNode("dict/integer"); 

现在你可以使用变量XmlEle来替换InnerText,因为它只是一个引用。

像这样:

 XmlEle.InnerText = TopNumber.ToString();