Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8220643
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T13:35:56+00:00 2026-06-07T13:35:56+00:00

I am attempting to modify a simple MS word templates XML. I realize there

  • 0

I am attempting to modify a simple MS word templates XML. I realize there are SDK’s available that could make this process easier but what I am tasked with maintaining uses packages and I was told to do the same.

I have a basic test document with two placeholders mapped to the following XML:

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

What I am doing is creating a stream using the word doc, removing the existing XML, getting some hard coded test XML and trying to write that to the stream.

Here is the code I am using:

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);

    }
}

This is currently not modifying the document although I feel like I am close to a solution. Any advice would be very much appreciated. Thanks!

Edit: To clairify, the result I am getting is the document is unchanged. I get no exceptions or the like, but the documents XML is not modified.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T13:35:58+00:00Added an answer on June 7, 2026 at 1:35 pm

    OK, so not quite the timely response I promised, but here goes!

    There are several aspects to the problem. Sample code is from memory and documentation, not necessarily compiled and tested.


    Read the template XML

    Before you delete the package part containing the template XML, you need to open its stream and read the XML. How you get the XML if the part doesn’t exist to begin with is up to you.

    My example code uses classes from the LINQ to XML API, though you could use whichever set of XML APIs you prefer.

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

    At this point you have an in-memory representation of the template XML in templateXml.


    Substitute values into the placeholders

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

    Check out the methods on XElement if you need to do anything more advanced than this, e.g. read the original content in order to determine the replacement value.


    Save the document

    This is your original code, modified and annotated.

    // 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.
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm attempting to modify an inherited project that has a convoluted process of displaying
I'm attempting to modify an applescript that fires a growl notification when there is
I'm attempting the modify this Modx Snippet so that it will accept multiple values
Attempting to make a NSObject called 'Person' that will hold the login details for
This is basically a menu that doesn't refresh the page. I am attempting to
I'm attempting to write an AJAX control extender that can modify an AJAX Control
I've been attempting to modify the contents of a custom tree view that inherits
I've been attempting to modify some code that I was using previously with jQuery
I'm attempting to modify a mySQL query (that works) to return a more specific
I'm attempting to recompile the Launcher2 (Gingerbread) application, so that i can modify it.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.