我需要从打开的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();
}
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?非常感谢.
如果只是替换表中的某些文本的问题,有几种方法可以解决它.
如果您可以控制要替换的文档,则可以将要替换的文本添加为书签,然后使用它
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);
}
Run Code Online (Sandbox Code Playgroud)
并完成它.如果要求您只需要使用表格中的文本来查找表格,我就会提出以下两个解决方案.
此解决方案假定您要在表格的单元格中查找确切的文本.
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;
Run Code Online (Sandbox Code Playgroud)
这是了解你的问题的一种方法.第二个是我们假设你想要匹配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;
Run Code Online (Sandbox Code Playgroud)
这两个示例都将返回您在其中找到字符串的表的xml.
但是我强烈建议您使用书签作为桌子的钩子.