Is there a way to replace a StructuredDocumentTag by a DocVariable

Hi!

I have a dotx file tha has some StructuredDocumentTags and I need to replace by DocVariables.
I tried some things but without success.

Do you have a sample code to do this?

@jean.heidemann If you need to put value of doc variable value, you can use code like this:

// Get SDT
StructuredDocumentTag tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);

// Set text of inline SDT to value of doc variable.
if (tag.Level == MarkupLevel.Inline)
{
    tag.RemoveAllChildren();
    tag.AppendChild(new Run(doc, doc.Variables["my_var"]));
}

If you need to insert a doc variable filed, you can achieve this using code like this:

Document doc = new Document("in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

// Get SDT
StructuredDocumentTag tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);

builder.MoveToStructuredDocumentTag(tag, 0);
builder.InsertField("DOCVARIABLE my_var");

I think i’m doing something wrong because the Docvariables wasn’t shown

I need to do this:

I want to replace all StructuredDocumentTags in the table and some others outside the table by DocVariables with same name like the example below the table

I tried using this two ways

StructuredDocumentTag tag = (StructuredDocumentTag)document.GetChild(NodeType.StructuredDocumentTag, 0, true);

builder.MoveToStructuredDocumentTag(tag, 0);
string text = tag.GetText();
text = text.Replace("\a", "");
builder.InsertField("DOCVARIABLE "+text);

foreach (StructuredDocumentTag sdt in document.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    builder.MoveToStructuredDocumentTag(sdt, 0);
    string text = sdt.GetText();
    text = text.Replace("\a", "");
    builder.InsertField("DOCVARIABLE "+text);
}

@alexey.noskov Thank you, I tried once changing the code I got it to work.

Here is my code:

foreach (StructuredDocumentTag sdt in document.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    builder.MoveToStructuredDocumentTag(sdt, 0);
    string text = sdt.GetText();
    text = text.Replace("\a", "")

    document.Range.Replace(text, "");
    builder.InsertField("DOCVARIABLE " + sdt.Title + " \\* MERGEFORMAT");

    sdt.RemoveSelfOnly();
}

@jean.heidemann It is perfect that you managed to achieve what you need. Please feel free to ask in case of any further issues. We are always glad to help you.