1

我正在尝试修改一个简单的 MS Word 模板 XML。我意识到有可用的 SDK 可以使这个过程更容易,但我的任务是维护使用包,我被告知要这样做。

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

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

我正在做的是使用单词 doc 创建一个流,删除现有的 XML,获取一些硬编码的测试 XML 并尝试将其写入流。

这是我正在使用的代码:

string strRelRoot = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
byte[] buffer = File.ReadAllBytes("dev.docx");
//stream with the template
MemoryStream stream = new MemoryStream(buffer, true);
//create a package using the stream
Package package = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);
PackageRelationshipCollection pkgrcOfficeDocument = package.GetRelationshipsByType(strRelRoot);
foreach (PackageRelationship pkgr in pkgrcOfficeDocument)
{
    if (pkgr.SourceUri.OriginalString == "/")
    {
        Uri uriData = new Uri("/customXML/item1.xml", UriKind.Relative);
        //remove the existing part
        if (package.PartExists(uriData))
        { 
            // Delete template "/customXML/item1.xml" part
            package.DeletePart(uriData);
        }
        //create a new part
        PackagePart pkgprtData = package.CreatePart(uriData, "application/xml");
        //test data
        string xml = @"<root>
                        <element>
                            Changed
                        </element>
                        <second>
                                The second placeholder changed
                        </second>
                    </root>";
        //stream created from the xml string
        MemoryStream fromStream = new MemoryStream();
        UnicodeEncoding uniEncoding = new UnicodeEncoding();
        byte[] fromBuffer = uniEncoding.GetBytes(xml);
        fromStream.Write(fromBuffer, 0, fromBuffer.Length);
        fromStream.Seek(0L, SeekOrigin.Begin);
        Stream toStream = pkgprtData.GetStream();
        //copy the xml to the part stream
        fromStream.CopyTo(toStream);
        //copy part stream to the byte stream
        toStream.CopyTo(stream);

    }
}

尽管我觉得我已经接近解决方案,但目前并未修改文档。任何建议将不胜感激。谢谢!

编辑:澄清一下,我得到的结果是文档没有改变。我没有任何异常或类似情况,但文档 XML 没有被修改。

4

1 回答 1

3

好的,所以不是我承诺的及时响应,但是就这样吧!

这个问题有几个方面。示例代码来自内存和文档,不一定经过编译和测试。


阅读模板 XML

在删除包含模板 XML 的包部分之前,您需要打开其流并读取 XML。如果该部分一开始不存在,您如何获取 XML 取决于您。

我的示例代码使用来自LINQ to XML API 的类,尽管您可以使用您喜欢的任何一组 XML API。

XElement templateXml = null;
using (Stream stream = package.GetPart(uriData))
    templateXml = XElement.Load(stream);
// Now you can delete the part.

此时,您在templateXml.


将值替换为占位符

templateXml.SetElementValue("element", "Replacement value of first placeholder");
templateXml.SetElementValue("second", "Replacement value of second placeholder");

如果您需要做比这更高级的事情,请查看XElement上的方法,例如阅读原始内容以确定替换值。


保存文档

这是您的原始代码,经过修改和注释。

// The very first thing to do is create the Package in a using statement.
// This makes sure it's saved and closed when you're done.
using (Package package = Package.Open(...))
{
    // XML reading, substituting etc. goes here.

    // Eventually...
    //create a new part
    PackagePart pkgprtData = package.CreatePart(uriData, "application/xml");
    // Don't need the test data anymore.
    // Assuming you need UnicodeEncoding, set it up like this.
    var writerSettings = new XmlWriterSettings
    {
        Encoding = Encoding.Unicode,
    };
    // Shouldn't need a MemoryStream at all; write straight to the part stream.
    // Note using statements to ensure streams are flushed and closed.
    using (Stream toStream = pkgprtData.GetStream())
    using (XmlWriter writer = XmlWriter.Create(toStream, writerSettings))
        templateXml.Save(writer);
    // No other copying should be necessary.
    // In particular, your toStream.CopyTo(stream) appeared
    // to be appending the part's data to the package's stream
    // (the physical file), which is a bug.
} // This closes the using statement for the package, which saves the file.
于 2012-07-12T11:29:26.570 回答