2017-07-14 80 views
0

檢索特定OPENXML元件Word文檔我在OpenXML格式狀元件路徑:如何通過元素路徑

/W:文件[1]/W:體[1]/W:P [1]

我需要從WordprocessingDocument得到這個元素作爲OpenXmlElement

事情是這樣的:

public OpenXmlElement GetElementByPath(WordprocessingDocument doc, string path) 
{ 
    // Some Logic 

    return element; 
} 

有人,請幫助

回答

0

使用XPath查詢(非常類似於您已寫入的內容)。

使用XmlDocument加載文件並從Document(root)節點獲取XPathNavigator的實例。

這裏是例如從我的代碼:

using System.Xml; 
    using System.Xml.Linq; 
    using System.Xml.XPath; 

public static List<XmlNode> queryXPath(this IXPathNavigable source, String xPath, XmlNamespaceManager nsManager = null) 
    { 
     XPathNavigator xNav = source.CreateNavigator(); 
     if (nsManager == null) nsManager = new XmlNamespaceManager(xNav.NameTable); 
     List<XmlNode> output = new List<XmlNode>(); 
     XPathExpression xExp = XPathExpression.Compile(xPath, nsManager); 
     XPathNodeIterator xIterator = xNav.Select(xExp); 
     while (xIterator.MoveNext()) 
     { 
      XmlNode tmp = xIterator.Current.UnderlyingObject as XmlNode; 

      output.Add(tmp); 
     } 
     return output; 
    }