Search code examples
c#xmlvstooutlook-addin

VSTO Word 2013 add in - Add Custom XML to document xml without it being visible on the page


I am attempting to add a string into the XML of a word document so that the user can not see the string on their document page but another piece of software can scan the document and find it in the XML.

I am using this information to write to the xml but it appears to be putting the string into a separate file called items1.xml.

https://msdn.microsoft.com/en-us/library/bb608612(v=vs.100).aspx

The code I am using is seen below:

private void AddCustomXmlPartToActiveDocument(Word.Document document)
{
    string xmlString =
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
    "<employees xmlns=\"http://schemas.microsoft.com/vsto/samples\">" +
        "<employee>" +
            "<name>Karina Leal</name>" +
            "<hireDate>1999-04-01</hireDate>" +
            "<title>Manager</title>" +
        "</employee>" +
    "</employees>";

Office.CustomXMLPart employeeXMLPart = document.CustomXMLParts.Add(xmlString);

}

How can I write a specified piece of text to the XML file where the page contents are stored?


Solution

  • The item#.xml files are where custom XML get stored, and it's the only way to store complex data in a Word document without it being a part of the document content. Another program can read it pretty easily, typically using the OpenXML SDK.

    So you're doing the right thing here, but whatever software needs to read this needs to look in the customXml folder for that item#.xml file, instead of the word/document.xml file. It will have to look for the namespace you defined.