2015-12-28 65 views
1

我正在使用Open XML SDK 2.6嘗試更新Word文檔&。我可以使用< w:tblCaption >元素來標識表格。我的問題是,我需要使用什麼Linq查詢來獲得對整個<結構的引用,給定一個具有某個<的表:wb:tblCaption > w:val屬性?OOXML - Linq使用某個標題提取Word表格

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

你可以嘗試這樣的事情:

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; 
} 

我不能在此刻測試,但我認爲它不應該離得太遠。