[英]Retrieve specific table element from open xml Word document mainpart
我需要从open xml文档中获取特定表的xml,其中innerText == "something" & "somethingelse"
示例:
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();
}
我该如何实现这一目标? 非常感谢。
如果只是替换表中的某些文本的问题,有几种方法可以解决它。
如果您可以控制要替换的文档,则可以将要替换的文本添加为书签,然后使用它
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);
}
并完成它。 如果要求您只需要使用表格中的文本找到表格,我就会提出以下两个解决方案。
此解决方案假定您要在表格的单元格中查找确切的文本。
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;
这是了解你的问题的一种方法。 第二个是我们假设你想要匹配整个表的部分innertext
。
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;
这两个示例都将返回您在其中找到字符串的表的xml。
但是我强烈建议您使用书签作为桌子的钩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.