We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Remove StructuredDocumentTag

I
a document with several StructuredDocumentTags I want to remove all but one, at
for that specific one I want to remove the SDT, but keep the content.
When
Remove() or RemoveSelfOnly() executed, the for each loop exit, hence only the
first SDT is handled.

var doc = new Document(fileName);
string tagName = "A";
foreach(var item in doc.GetChildNodes(NodeType.StructuredDocumentTag, true, true))
{
    var sdt = (StructuredDocumentTag)item;
    if (sdt.Tag.Equals(tagName))
        sdt.RemoveSelfOnly();
    else
        sdt.Remove();
}

What is wrong with the code?

Hi Henrik,

Thanks for your inquiry.

You are invalidating the enumerator when removing one of the structured document tags which causes the loop to exit early. Instead, try using the code below:

var doc = new Document(fileName);
string tagName = "A";
Node[] tags = doc.GetChildNodes(NodeType.StructuredDocumentTag, true, true)).ToArray();
foreach(var item in tags)
{
    var sdt = (StructuredDocumentTag) item;
    if (sdt.Tag.Equals(tagName))
        sdt.RemoveSelfOnly();
    else
        sdt.Remove();
}

Thanks,