Storing Hidden XML In Word

Published 14 November 03 09:35 AM | chris 
A fellow reader (Cyril Mathey) of the microsoft.public.office.xml newsgroup posed an interesting question: How can I hide XML in a Word document?

This is a good question. There are times where you may want to store configuration related data or some form of Meta data. However, Word doesn’t support Hidden XML. So I have a hack! WARNING: This hasn’t been thoroughly tested :-)

We can use Word Document variables to store XML. Document variables are a cool and often unused feature of Microsoft Word. It allows a programmer to persist Meta information with the document. This information is not visible to the user, only to your code. This gives it an advantage over Document properties because users cannot edit them. It’s a great way to hide persistant data.

So programmatically I can add a document variable using:

ActiveDocument.Variables.Add "MyXML", "<Config><var1>True</var1><var2>False</var2></Config>";

So we have now stored the following XML in the document:

<Config><var1>True</var1><var2>False</var2></Config>

This XML snippet is now stored in a document variable called MyXML and will travel with the document. To retrieve it programmatically:

Debug.Print ActiveDocument.Variables("MyXml")

However, is it possible to use document variables with WordML XML documents? YES! When I saved the document using the previously discussed code, the following is stored in the XML:

<w:docVars>
<w:docVar w:name="MyXML" w:val="&lt;Config&gt;&lt;var1&gt;True&lt;/var1&gt;
&lt;var2&gt;False&lt;/var2&gt;&lt;/Config&gt;"/>
</w:docVars>
</w:docPr>”

As you can see the XML is stored in an attribute of the docVar element and it is encoded.

In summary, we can store hidden XML in a document. We can programmatically retrieve it through the Word Object Model using Document.Variables or from the raw XML of a WordML document.

Comments

No Comments
Anonymous comments are disabled