问题
I'm using the Open XML SDK 2.6 to try & update a Word Document. I can use the <w:tblCaption> element to identify a table. My question is, what Linq query do I need to use to get a reference to entire <w:tbl> structure, given a table with a certain <w:tblCaption> w:val attribute?
DocumentFormat.OpenXml.Packaging.WordprocessingDocument doc = WordprocessingDocument.Open(@"D:\dev\openxml\table.docx", false);
var tables = doc.MainDocumentPart.Document.Descendants<Table>().ToList();
//WHAT LINQ STATEMENT DO I USE?
DOCX TBL XML
<w:tbl>
<w:tblPr>
<w:tblW w:w="4814" w:type="dxa"/>
<w:tblInd w:w="247" w:type="dxa"/>
<w:tblBorders>
<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/>
</w:tblBorders>
<w:tblLayout w:type="fixed"/>
<w:tblLook w:val="0000" w:firstRow="0" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="0"/>
<w:tblCaption w:val="TBL_TEST"/>
</w:tblPr>
<w:tblGrid>
<w:gridCol w:w="1468"/>
<w:gridCol w:w="1444"/>
<w:gridCol w:w="1902"/>
</w:tblGrid>
<w:tr>
</w:tr>
</w:tbl>
回答1:
You can try something like this:
XDocument doc;
XNamespace ns =
XNamespace.Get(@"http://schemas.openxmlformats.org/wordprocessingml/2006/main");
using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
using (StreamReader sr = new StreamReader(doc.MainDocumentPart.GetStream()))
using (XmlReader xr = XmlReader.Create(sr))
xdoc = XDocument.Load(xr);
XElement table;
//Descendants() gets all children,grandchildren etc.
//First get document -> body ->
XElement tablecapt = xdoc.Elements().First().Elements().First()
.Descendants().Where(d => d.Name == XName.Get("tblCaption", ns)
&& d.Value == "TBL_TEST").FirstOrDefault();
if (tablecapt != null)
table = tablecapt.Parent.Parent;
}
I can't test it at the moment, but I think it shouldn't be too far off.
来源:https://stackoverflow.com/questions/34501314/ooxml-linq-to-extract-word-tables-with-a-certain-caption