I am using the DocumentVisitor functionality to remove all fields from my documents(see below). There are some nested fields in my document that are not being unlinked properly. How can I properly unlink nested fields?
The field code in my original document is: {IF {DOCPROPERTY "~V_02"} = "1" "A" "B"}
In my document after applying the RemoveFields class below the field reads: {IF = "1" "A" "B"}
I would like my final document to say just : A or B with the field being unlinked
(I also tried another method to unlink the fields(see code below) which produced the same results.
How would I do this correctly?
- public class RemoveFields : DocumentVisitor
- {
- private bool _delete = false;
- public override VisitorAction VisitFieldStart(Aspose.Words.Fields.FieldStart fieldStart)
- {
- if (fieldStart.FieldType == FieldType.FieldDocProperty || fieldStart.FieldType == FieldType.FieldCreateDate)
- {
- _delete = true;
- fieldStart.Remove();
- }
- return VisitorAction.Continue;
- }
- public override VisitorAction VisitFieldSeparator(Aspose.Words.Fields.FieldSeparator fieldSeparator)
- {
- if (fieldSeparator.FieldType == FieldType.FieldDocProperty || fieldSeparator.FieldType == FieldType.FieldCreateDate)
- {
- _delete = false;
- fieldSeparator.Remove();
- }
- return VisitorAction.Continue;
- }
- public override VisitorAction VisitFieldEnd(Aspose.Words.Fields.FieldEnd fieldEnd)
- {
- if (fieldEnd.FieldType == FieldType.FieldDocProperty || fieldEnd.FieldType == FieldType.FieldCreateDate)
- {
- _delete = false;
- fieldEnd.Remove();
- }
- return VisitorAction.Continue;
- }
- public override VisitorAction VisitRun(Run run)
- {
- if (_delete)
- run.Remove();
- return VisitorAction.Continue;
- }
- }
I also tried the following code, which produces the same result:
- private static void UnlinkFields(Document doc)
- {
- ArrayList propertyStarts = new ArrayList();
- NodeCollection starts = doc.GetChildNodes(NodeType.FieldStart, true);
- foreach (FieldStart start in starts)
- {
- if (start.FieldType == FieldType.FieldDocProperty)
- {
- propertyStarts.Add(start);
- }
- }
- foreach (FieldStart start in propertyStarts)
- {
- Node currentNode = start;
- Node fieldSeparator = null;
- while (currentNode.NodeType != NodeType.FieldSeparator && currentNode.NodeType != NodeType.FieldEnd)
- {
- currentNode = currentNode.NextSibling;
- currentNode.PreviousSibling.Remove();
- }
- if (currentNode.NodeType == NodeType.FieldSeparator)
- {
- fieldSeparator = currentNode;
- while (currentNode != null && currentNode.NodeType != NodeType.FieldEnd)
- {
- currentNode = currentNode.NextSibling;
- }
- fieldSeparator.Remove();
- }
- if (currentNode != null)
- currentNode.Remove();
- }
- }