繁体   English   中英

如何通过元素路径检索特定的openXML元素Word文档

[英]How to retrieve specific openXML element Word document by element path

我有openXML格式的元素路径,例如:

/ w:document [1] / w:body [1] / w:p [1]

我需要从WordprocessingDocument获取此元素作为OpenXmlElement

像这样:

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

    return element;
}

有人请帮忙

使用XPath查询(非常类似于您已经编写的内容)。

使用XmlDocument加载文件,并从Document(根)节点获取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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM