Remove Document variables for OpenXML DOCX?
I'm trying to remove the doc
variables from a DOCX file. Here is the code I'm using, but it doesn't remove any...
This is the complete code:
class Program
{
static void Main(string[] args)
{
string filePath = "C:\\..\\..sample.docx";
Remove removedocvars = new Remove();
removedocvars.RemoveDocVariables(filePath);
}
}
//method to开发者_如何学Python remove doc vars
public void RemoveDocVariables(string fileName)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
{
List<DocumentVariables> DocVarsToDelete = doc.MainDocumentPart.RootElement.Descendants<DocumentVariables>().ToList();
foreach (DocumentVariables dc in DocVarsToDelete)
{
dc.Remove();
}
doc.MainDocumentPart.Document.Save();
}
}
the variables are in the settings.xml file, so you have to use MainDocumentPart.DocumentSettingsPart.Settings.Descendants<>().
public void RemoveDocVariables(string fileName)
{
using (var doc = WordprocessingDocument.Open(fileName, true))
{
doc.MainDocumentPart.DocumentSettingsPart.Settings.RemoveAllChildren<DocumentVariables>();
}
}
If this is the extent of your code, then aren't you missing a call to the save method?
Something like:
foreach (DocumentVariable dc in DocVarsToDelete)
{
dc.Remove();
}
document.Save();
This is a 6 years old question, but I think it still would be valuable to add the answer. Your issue likely is related to this:
https://github.com/OfficeDev/Open-XML-SDK/issues/198
https://github.com/OfficeDev/Open-XML-SDK/issues/222
OpenXML used to be not like mixing of accessing mechanism until the patch mentioned in one of the link above was applied.
精彩评论