繁体   English   中英

如何使用C#覆盖DOCX XML文件?

[英]How do I overwrite a DOCX XML file with C#?

我被卡住了。 目标是仅当相应的date属性在给定日期之后,才使用C#工具更改MS Word跟踪更改中的审阅者姓名。 变量字符串docPath传递给方法changeRevAuthor docPath代表打开的DOCX文件。 传递文件时必须将其打开,因为该工具还会在运行该方法之前将所有DOC文件保存为DOCX。

作者姓名被更改,并且XML文件中的日期已正确确认。 我们通过将XML保存到静态路径进行了测试。 但是,我需要做的实际上是覆盖现有的XML文件,而不是将其拉出并保存到其他位置。 这是现有方法:

    private void changeRevAuthor(string docPath)
    {
        using (Stream stream = System.IO.File.Open(docPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {  
            stream.Seek(0, SeekOrigin.End); 
            XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            WordprocessingDocument document = WordprocessingDocument.Open(stream, false);
            XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();          
            var nodes = mainDocumentXDoc.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);
            var currentdate = "2016-06-21";

            foreach (XElement node in nodes)
            {
                var date = node.Attribute(w + "date").ToString().Substring(8, 10);
                if (DateTime.Parse(date) < DateTime.Parse(currentdate))
                {
                    node.SetAttributeValue(w + "author", "LUZ");
                    Debug.WriteLine(date);
                }                   
            }
            mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));

        }
    }

通过研究,我相信最后一行应该可以解决问题: mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));

但是,这将返回以下错误:

在System.IO.Packaging.dll中发生“类型为'System.IO.IOException的未处理的异常'。 。”

当我将其更改为FileAccess.WriteFileAccess.ReadWrite ,收到以下错误:

'其他信息:该进程无法访问文件'C:\\ Users .... \\ Desktop \\ C#Test \\ Results \\ newtest.docx',因为该文件正在被另一个进程使用。'

我从这里去哪里?

谢谢卢克

这可以解决您的问题:

void changeRevAuthor (string docPath)
{
  XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
  WordprocessingDocument document = WordprocessingDocument.Open(docPath, true);
  XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();

  var nodes = mainDocumentXDoc.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);

  foreach (XElement node in nodes)
  {
    // ...
    node.SetAttributeValue(w + "author", "LUZ");        
  }
  mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));
}

不完整

您还应该修改word \\ commentsdocProps \\ core软件包部分,而不仅限于word \\ document

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM