2017-07-14 57 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; 
    }