none
Using Office.js WORD Add-in, how to a create a custom XML and store it in a WORD document? RRS feed

  • Question

  • Using Office.js WORD Add-in, how can a create a custom XML and store it in a  WORD document? I just need a very simple example.
    • Edited by namwam Friday, October 19, 2018 12:42 AM
    Friday, October 19, 2018 12:41 AM

Answers

  • Hi namwam,

    My test environment is Visual Studio 2015,Office2016.
    To create a Word Web add-in, follow these steps:


    Then add two methods to home.html, insertParagraph() and addXMLPart(). The addXMLPart method is custom and you can name it as you wish. 

    Please see the following code:

    /// <reference path="../App.js" />
    
    (function () {
        "use strict";
    
        // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
               
               $('#get-data-from-selection').click(insertParagraph);
            });
        };
    
        // Reads data from current document selection and displays a notification
        function getDataFromSelection() {
            Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        app.showNotification('The selected text is:', '"' + result.value + '"');
                    } else {
                        app.showNotification('Error:', result.error.message);
                    }
                }
            );
        }
    
        function insertParagraph() {
            Word.run(function (context) {
    
                // TODO4: Queue commands to insert a paragraph into the document.
                //const docBody = context.document.body;
                //docBody.insertParagraph("Office has several versions, including Office 2016, Office 365 Click-to-Run, and Office Online.",
                //                       "Start");
                var xmlObj = "<data>My encoded data.</data>";
                addXMLPart();
                return context.sync();
            })
            .catch(function (error) {
                console.log("Error: " + error);
                if (error instanceof OfficeExtension.Error) {
                    console.log("Debug info: " + JSON.stringify(error.debugInfo));
                }
            });
        }
         
         //Custom function
        function addXMLPart() {
            Office.context.document.customXmlParts.addAsync('<root categoryId="1" xmlns="http://tempuri.org"><item name="Cheap Item" price="$193.95"/><item name="Expensive Item" price="$931.88"/></root>', function (result) { });
        }
    
    
    })();

    Then run the program.
    Then click the Get data from selection button, as shown below:

    At this point, the XML data has been written to the Word document, but we can't see it.
    Then manually save the document, such as to the D disk, as shown below:


    At this time, you still cannot see the XML content in the Word document. You need to change the extension of Word document to zip, as shown below:

    Then unzip doc22.zip.

    Go to the D: Doc22\customXml directory and you can see item1.xml, which is the final result. You can see that the contents of this file are what we wrote to the Word document.

    Hopefully it helps you.

    Best Regards,
    Bruce


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Monday, October 22, 2018 7:40 AM
    Moderator

All replies

  • Hi namwam,

    You can create a word web add-in by using VS and replace the following code:

    function addXMLPart() {
        Office.context.document.customXmlParts.addAsync(
            '<root categoryId="1" xmlns="http://tempuri.org"><item name="Cheap Item" price="$193.95"/><item name="Expensive Item" price="$931.88"/></root>',
            function (result) {});
    }
    More information about CustomXmlParts, please see Office.CustomXmlParts interface

    Then you will see the Custom folder in your word file. Please refer the following screenshot:

     

    Reference link: Custom XML Parts

    Regards,

    Bruce


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Friday, October 19, 2018 11:43 AM
    Moderator
  • Bruce,

    I did not understand your response. Could you please clarify?

    I created a Word web add-in from following Microsoft tutorial but I don't see the function addXMLPart(…). Could you please explain as follows:

    • Step 1: Create a WORD web add-in using VS
    • Step 2: Do this.....

    Or, point me to a latest article that creates a custom xml part in MS WORD web add-in. All the examples I searched online are at least four to five years old.


    • Edited by namwam Friday, October 19, 2018 4:21 PM
    Friday, October 19, 2018 4:19 PM
  • Hi namwam,

    My test environment is Visual Studio 2015,Office2016.
    To create a Word Web add-in, follow these steps:


    Then add two methods to home.html, insertParagraph() and addXMLPart(). The addXMLPart method is custom and you can name it as you wish. 

    Please see the following code:

    /// <reference path="../App.js" />
    
    (function () {
        "use strict";
    
        // The initialize function must be run each time a new page is loaded
        Office.initialize = function (reason) {
            $(document).ready(function () {
                app.initialize();
               
               $('#get-data-from-selection').click(insertParagraph);
            });
        };
    
        // Reads data from current document selection and displays a notification
        function getDataFromSelection() {
            Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
                function (result) {
                    if (result.status === Office.AsyncResultStatus.Succeeded) {
                        app.showNotification('The selected text is:', '"' + result.value + '"');
                    } else {
                        app.showNotification('Error:', result.error.message);
                    }
                }
            );
        }
    
        function insertParagraph() {
            Word.run(function (context) {
    
                // TODO4: Queue commands to insert a paragraph into the document.
                //const docBody = context.document.body;
                //docBody.insertParagraph("Office has several versions, including Office 2016, Office 365 Click-to-Run, and Office Online.",
                //                       "Start");
                var xmlObj = "<data>My encoded data.</data>";
                addXMLPart();
                return context.sync();
            })
            .catch(function (error) {
                console.log("Error: " + error);
                if (error instanceof OfficeExtension.Error) {
                    console.log("Debug info: " + JSON.stringify(error.debugInfo));
                }
            });
        }
         
         //Custom function
        function addXMLPart() {
            Office.context.document.customXmlParts.addAsync('<root categoryId="1" xmlns="http://tempuri.org"><item name="Cheap Item" price="$193.95"/><item name="Expensive Item" price="$931.88"/></root>', function (result) { });
        }
    
    
    })();

    Then run the program.
    Then click the Get data from selection button, as shown below:

    At this point, the XML data has been written to the Word document, but we can't see it.
    Then manually save the document, such as to the D disk, as shown below:


    At this time, you still cannot see the XML content in the Word document. You need to change the extension of Word document to zip, as shown below:

    Then unzip doc22.zip.

    Go to the D: Doc22\customXml directory and you can see item1.xml, which is the final result. You can see that the contents of this file are what we wrote to the Word document.

    Hopefully it helps you.

    Best Regards,
    Bruce


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Monday, October 22, 2018 7:40 AM
    Moderator
  • Hi namwam,

    This thread has been around for a long time. Please remember to mark the replies as answers if they helped. Please help us close the thread.

    Thank you for understanding! If you have any question, or update, please feel free to let me know.
    I wish you a happy life!

    Best Regards,
    Bruce

    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.


    Wednesday, October 24, 2018 10:17 AM
    Moderator
  • Bruce, thank you.

    I have another question regarding using window.open(...) method in an Office.js add-in. In my add-in, it is not working. Do you have any suggestions? I have posted the question here.

    Regards,

    Nam

    Saturday, November 3, 2018 5:33 PM