更改Word文档XML

时间:2012-07-11 12:11:27

标签: c# xml ms-word

我正在做的是尝试更改Microsoft Office Word文档XML的值并将其另存为新文件。我知道有一些SDK可以用来使这更容易,但我负责维护的项目是这样做的,我被告知我也必须这样做。

我有一个基本的测试文档,其中两个占位符映射到以下XML:

<root>
  <element>
     Fubar
  </element>
  <second>
     This is the second placeholder
  </second>
</root>

在我的测试项目中,我有以下内容:

string strRelRoot = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
//the word template
byte[] buffer = File.ReadAllBytes("dev.docx");
MemoryStream stream = new MemoryStream(buffer, true);
Package package = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);
//get the document relationship
PackageRelationshipCollection pkgrcOfficeDocument = package.GetRelationshipsByType(strRelRoot);
//iterate through relationship
foreach (PackageRelationship pkgr in pkgrcOfficeDocument)
{
    if (pkgr.SourceUri.OriginalString == "/")
    {
        //uri for the custom xml
        Uri uriData = new Uri("/customXML/item1.xml", UriKind.Relative);
        //delete the existing xml if it exists
        if (package.PartExists(uriData))
        { 
            // Delete template "/customXML/item1.xml" part
            package.DeletePart(uriData);
        }
        PackagePart pkgprtData = package.CreatePart(uriData, "application/xml");
           //hard coded test data
           string xml = @"<root>
                        <element>
                            Changed
                        </element>
                        <second>
                                The second placeholder changed
                        </second>
                    </root>";
        Stream fromStream = pkgprtData.GetStream();
        //write the string
        fromStream.Write(Encoding.UTF8.GetBytes(xml),0,xml.Length);
        //destination file
        Stream dest = File.Create("test.docx");
        //write to the destination file
        for (int a = fromStream.ReadByte(); a != -1; a = fromStream.ReadByte())
        {
            dest.WriteByte((byte)a);
        }

    }
}

现在正在发生的是正在创建文件test.docx,但它是一个空白文档。我不确定为什么会这样。任何人都可以提供有关此方法的任何建议和/或我正在做的错误将非常感谢。非常感谢!

1 个答案:

答案 0 :(得分:2)

fromStream.Write调用之后,流指针位于您刚写入的数据之后。因此,您对fromStream.ReadByte的第一次调用已经在流的末尾,并且您没有阅读(和写入)。

在写入之后你需要Seek到流的开头(如果包返回的流支持搜索),或者关闭fromStream(以确保你写的数据被刷新)并重新打开它进行阅读。

fromStream.Seek(0L, SeekOrigin.Begin);