我正在做的是尝试更改 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,但它是一个空白文档。我不确定为什么会这样。任何人都可以就这种方法和/或我做错的事情提出任何建议,我们将不胜感激。非常感谢!