我需要从打开的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。
但是我强烈建议你使用书签作为一个钩子到你的表