Retrieve specific table element from open xml Word document mainpart
c#, openxml
Solution
If it is just a question of replacing some text in a table, there are several ways you can go about it.
If you have control over the document you are replacing in, you can just bookmark the text you want to replace, then use this
public void ReplaceInBookmark(BookmarkStart bookmarkStart, string text)
{
OpenXmlElement elem = bookmarkStart.NextSibling();
while (elem != null && !(elem is BookmarkEnd))
{
OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
bookmarkStart.Parent.InsertAfter<Run>(new Run(new Text(text)), bookmarkStart);
}
and be done with it. If it is a requirement that you just HAVE to find the table using only the text inside the table, I proprose the two following solutions.
This solution assumes you want to find the exact text, in a cell in the 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 = from c in cellList where c.InnerText == "Testing123" ||
c.InnerText == "TestingOMG!"
select c.Parent.Parent;
String xml = q.First().OuterXml;
That's one way to understand your question. The second one is where we assume you want to match up to part of the `innertext` of the table as whole.
var tables = mainPart.Document.Descendants<Table>().ToList();
var q = from c in tables where c.InnerText.Contains("Testing123") ||
c.InnerText.Contains("TestingOMG!") select c;
String xml = q.First().OuterXml;
Both examples will return the xml of the table you find the string in.
However I would strongly advise that you make use of a bookmark as a hook to your table.
Problem
I need do get a specific table's xml from open xml document where `innerText == "something" & "somethingelse"` Example : ``` using (WordprocessingDocument doc = WordprocessingDocument.Open(path, false)) { MainDocumentPart mainPart = doc.MainDocumentPart; string xml = mainPart.Document.Descendants<Table>().Select // where 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 do I achieve this ? many thanks.