[英]Delete an altChunk
How can I successfully delete an altChunk with a given id from a document. 如何从文档中成功删除具有给定ID的altChunk。 The process that I'm following is -
我要遵循的过程是-
MainDocumentPart mainPart = theDoc.MainDocumentPart;
mainPart.DeletePart(mainPart.GetPartById("AltChunkIdA1"));
I'm adding the altChunk after a given sdt. 我在给定的sdt之后添加altChunk。 For adding an altChunk, I've the following code -
要添加altChunk,我需要以下代码-
string altSchedChunkId = "AltChunkIdA1";
AlternativeFormatImportPart schedChunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altSchedChunkId);
schedChunk.FeedData(File.Open(FileA12, FileMode.Open));
AltChunk altSchedChunk = new AltChunk();
altSchedChunk.Id = altSchedChunkId;
OpenXmlElement parent = sdtRunSchedTerms.Parent;
parent.InsertAfter(altSchedChunk, sdtRunSchedTerms);
But it doesn't seem to work out. 但这似乎无法解决。 Instead of the altChunk getting deleted, a new altChunk with the same id is added every time I try editing the document.
每次删除文档时,都会添加一个具有相同ID的新altChunk,而不是删除altChunk。
Thanks in advance, 提前致谢,
Neha NEHA
I had the same issue with chunks, but I think I solved it. 我在块方面也遇到了同样的问题,但我想我已经解决了。
If you look carefully at the code to add a chunk, you see that it actually does two things: 如果仔细查看添加块的代码,您会发现它实际上做了两件事:
AddAlternativeFormatImportPart
) AddAlternativeFormatImportPart
) and 和
InsertAfter
). InsertAfter
)添加对块的引用。 The code in which you delete the chunk does not delete the reference to the chunk. 在其中删除块的代码不会删除对该块的引用。 If you then add a new chunk with the same id and add a reference, you will end up with your chunk appearing twice.
如果然后添加具有相同ID的新块并添加引用,则最终将使块出现两次。
See AltChunk class documentation on MSDN for more details. 有关更多详细信息,请参见MSDN上的AltChunk类文档 。
I use this code to remove any existing references to a chunk. 我使用此代码删除了对块的任何现有引用。
var altChunks = mainPart.RootElement.Descendants<AltChunk>().Where(e => e.Id == altChunkId);
foreach (var altChunk in altChunks)
{
altChunk.Remove();
}
After that, you can use DeletePart()
to delete the chunk itself. 之后,您可以使用
DeletePart()
删除块本身。
I must admit that I found this by trial and error, so I am not 100% sure it is the recommended way to do it, but it appears to work. 我必须承认我是通过反复试验发现的,所以我不是100%确信这是推荐的方法,但是它似乎可以工作。
To get a better feeling about what a chunk actually is, I unzipped a .docx-file ( 7-zip is willing to do this) and found a directory word which contains chunks, as well as a directory _rels with a file document.xml.rels inside. 为了更好地了解实际上是什么块,我解压缩了一个.docx文件( 7-zip愿意这样做),并找到了包含块的目录字 ,以及带有文件document.xml的目录_rels 。 .rels里面。 The latter lists the references to the chuncks, ie where they should be inserted.
后者列出了对块的引用,即应将它们插入的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.