Free Support Forum - aspose.com

Empty Doc.Variables; Replace Variable with Merge field

I've loaded a word doc into an the aspose word document object and I'm not seeing anything in the Variables property (Enumeration yields no results). The word doc being loaded does in fact have many docvariable fields. Any common issues with accessing the Variables collection programatically?

Also - once I've solved that puzzle, I have a requirement to convert the docvariable fields to merge fields. I found something similar in a previous post but it deals only with plain text.

http://www.aspose.com/community/forums/permalink/372922/372922/showthread.aspx#372922

Is it possible to load a doc and convert { DOCVARIABLE FIRST_NAME } to { MERGEFIELD FIRST_NAME } ?

Hi Brett,


Thanks for your inquiry. If your query is related to Document’s Variables, you can get Document’s variables by Document.Variables property. Please see the following code snippet for your kind refernece.
http://www.aspose.com/docs/display/wordsnet/Getting+Document+Variables

<span style=“font-size:
10.0pt;font-family:“Courier New”;color:#2B91AF;mso-no-proof:yes”>Document<span style=“font-size:10.0pt;font-family:“Courier New”;mso-no-proof:yes”> doc = new Document();<o:p></o:p>

for (int i = 0; i < 10; i++)

doc.Variables.Add("Var " + i, "Value " + i);

foreach (DictionaryEntry entry in doc.Variables)

{

string name = entry.Key.ToString();

string value = entry.Value.ToString();

// Do something useful.

Console.WriteLine("Name: {0}, Value: {1}", name, value);

}


You can also get the DocVariable Fields by using following code snippet and replace DocVariable Fields with Mail Merge fields.


Document doc = new Document(MyDir + "in.docx");

DocumentBuilder builder = new DocumentBuilder(doc);

foreach (FieldStart fStart in doc.GetChildNodes(NodeType.FieldStart, true))

{

if (fStart.FieldType == FieldType.FieldDocVariable)

{

builder.MoveToField(fStart.GetField(), false);

FieldStart DocVarfield = (FieldStart)builder.CurrentNode;

String[] fieldcodes = fStart.GetField().GetFieldCode().Trim().Split(new Char[] { ' ' });

if (fieldcodes[2] != "")

{

builder.InsertField(@"MERGEFIELD " + fieldcodes[2] + @" \* MERGEFORMAT");

DocVarfield.GetField().Remove();

}

}

}

doc.Save(MyDir + "out.docx");


Moreover, a field in a Word document is a complex structure consisting of multiple nodes that include field start, field code, field separator, field result and field end. Fields can be nested, contain rich content and span multiple paragraphs or sections in a document. The Field class is a "facade" object that provides properties and methods that allow to work with a field as a single object.
http://www.aspose.com/docs/display/wordsnet/Field+Class

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.