DomZ
April 29, 2024, 6:51am
1
Hello,
I load a document and I need to get all tables (Aspose.Words.Table) between two strings.
Example :
table0
LOOP2_START
table1
paragraph1
paragraph2
table2
LOOP2_END
table3
I need a method to get table1 and table2 between LOOP2_START and LOOP2_END .
Thanks
@DomZ "LOOP2_START"
and "LOOP2_END"
makers are separate paragraph you can use DocumentVisitor to achieve this:
Document doc = new Document(@"C:\Temp\in.docx");
doc.Accept(new MyVisitor());
private class MyVisitor : DocumentVisitor
{
public override VisitorAction VisitParagraphStart(Paragraph paragraph)
{
string paraText = paragraph.ToString(SaveFormat.Text).Trim();
if (paraText == "LOOP2_START")
mProccessTables = true;
else if (paraText == "LOOP2_END")
mProccessTables = false;
return VisitorAction.Continue;
}
public override VisitorAction VisitTableStart(Table table)
{
if (mProccessTables)
{
// Process the table here
Console.WriteLine("This table is between LOOP2_START and LOOP2_END markers");
}
return VisitorAction.Continue;
}
private bool mProccessTables = false;
}
DomZ
April 29, 2024, 9:53am
3
Thanks @alexey.noskov .
It works great.
Do you know if it is possible to do it without using a visitor ?
I can find the start and the end of the document block with this :
var loopStart = document.FindSeq<Node>(x => x.GetText().Contains("LOOP2_START")).FirstOrDefault();
var loopEnd = document.FindSeq<Node>(x => x.GetText().Contains("LOOP2_END")).FirstOrDefault();
But I don’t know how to get tables between those 2 nodes …
Thanks
@DomZ You can use something like this:
Document doc = new Document(@"C:\Temp\in.docx");
Node loopStart = doc.GetChildNodes(NodeType.Paragraph, true).Where(x => x.GetText().Contains("LOOP2_START")).FirstOrDefault();
Node loopEnd = doc.GetChildNodes(NodeType.Paragraph, true).Where(x => x.GetText().Contains("LOOP2_END")).FirstOrDefault();
List<Table> tablesBetween = doc.GetChildNodes(NodeType.Any, true)
.SkipWhile(n => n != loopStart)
.TakeWhile(n => n != loopEnd)
.Where(n => n.NodeType == NodeType.Table)
.Cast<Table>()
.ToList();
DomZ
April 29, 2024, 12:09pm
5
Thanks it works like a charm !
1 Like