删除OpenXML DOCX的文档变量?

时间:2010-12-02 21:19:30

标签: c# openxml openxml-sdk

我正在尝试从DOCX文件中删除doc个变量。这是我正在使用的代码,但它不会删除任何...

这是完整的代码:

class Program
    {
        static void Main(string[] args)
        {
            string filePath = "C:\\..\\..sample.docx";
            Remove removedocvars = new Remove();
            removedocvars.RemoveDocVariables(filePath);

        }
    }

//method to 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();
            }
        }

3 个答案:

答案 0 :(得分:1)

变量位于settings.xml文件中,因此您必须使用MainDocumentPart.DocumentSettingsPart.Settings.Descendants&lt;&gt;()。

public void RemoveDocVariables(string fileName)
{
    using (var doc = WordprocessingDocument.Open(fileName, true))
    {
        doc.MainDocumentPart.DocumentSettingsPart.Settings.RemoveAllChildren<DocumentVariables>();
    }
}

答案 1 :(得分:0)

如果这是您的代码范围,那么您是否错过了对save方法的调用?

类似的东西:

    foreach (DocumentVariable dc in DocVarsToDelete)
    {
        dc.Remove();
    } 
    document.Save();

答案 2 :(得分:0)

这是一个6年前的问题,但我认为添加答案仍然很有价值。您的问题可能与此有关:

https://github.com/OfficeDev/Open-XML-SDK/issues/198

https://github.com/OfficeDev/Open-XML-SDK/issues/222

OpenXML曾经不同于访问机制的混合,直到应用了上述链接中提到的补丁。

相关问题