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.
https://forum.aspose.com/t/61710
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.
https://docs.aspose.com/words/net/work-with-document-properties/
Document doc = new Document();
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.
https://reference.aspose.com/words/net/aspose.words.fields/field/
Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.