c# - Retrieve specific table element from open xml Word document mainpart -


i need specific table's xml open xml document innertext == "something" & "somethingelse"

example :

using (wordprocessingdocument doc = wordprocessingdocument.open(path, false)) {     maindocumentpart mainpart = doc.maindocumentpart;     string xml = mainpart.document.descendants<table>().select // innertext == "this" || innertext == "that"     console.writeline(xml);      maindocumentpart documentprincipal = document.maindocumentpart;     documentprincipal.document.innerxml =    documentprincipal.document.innerxml.replace(replacethisby, that);     documentprincipal.document.save();     document.dispose(); } 

how achieve ? many thanks.

if question of replacing text in table, there several ways can go it.

if have control on document replacing in, can bookmark text want replace, use this

public  void replaceinbookmark(bookmarkstart bookmarkstart, string text)     {         openxmlelement elem = bookmarkstart.nextsibling();         while (elem != null && !(elem bookmarkend))         {             openxmlelement nextelem = elem.nextsibling();             elem.remove();             elem = nextelem;         }         bookmarkstart.parent.insertafter<run>(new run(new text(text)), bookmarkstart);     } 

and done it. if requirement have find table using text inside table, proprose 2 following solutions.

this solution assumes want find exact text, in cell in table.

var tables = mainpart.document.descendants<table>().tolist(); list<tablecell> celllist = new list<tablecell>(); foreach (table t in tables) {     var rows = t.elements<tablerow>();     foreach (tablerow row in rows)     {         var cells = row.elements<tablecell>();         foreach (tablecell cell in cells)          celllist.add(cell);     } } var q = c in celllist c.innertext == "testing123" ||                                   c.innertext == "testingomg!"          select c.parent.parent;  string xml = q.first().outerxml; 

that's 1 way understand question. second 1 assume want match part of innertext of table whole.

var tables = mainpart.document.descendants<table>().tolist(); var q = c in tables c.innertext.contains("testing123") ||                                c.innertext.contains("testingomg!") select c; string xml = q.first().outerxml; 

both examples return xml of table find string in.

however advise make use of bookmark hook table.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -